Common Table Expression(CTE) 는 SQL에서 사용하는 임시 결과입니다. 아주 길고 큰 쿼리에서 CTE는 전체의 일부를 표현하는 작은 쿼리가 됩니다.
CTE의 장점은 아래와 같습니다.
* 쿼리에서 특정 부분이 어떤 일을 하는지 구조화
* 의존하는 테이블 명시
* 간단한 디버깅
다시 말해, CTE 방식은 쿼리를 구조화해서 복잡성을 낮추고 의존성을 드러내서 디버깅이 간단해지게 합니다.
CTE를 활용한 예제는 아래와 같습니다.
1. orders 테이블을 Import 하고,
2. 1번에서 가져온 테이블을 유저별로 집계 합니다.
3. 2번에서 집계한 값으로 유저 세그먼트를 나눕니다.
4. 세그먼트까지 나눈 결과 테이블을 조회합니다.
```
with import_orders as (
select * from orders
),
aggregate_orders as (
select
customer_id,
count(order_id) as count_orders
from import_orders
where status not in ('returned', 'return pending')
group by 1
),
segment_users as (
select
*,
case
when count_orders >= 3 then 'super_buyer'
when count_orders <3 and count_orders >= 2 then
'regular_buyer'
else 'single_buyer'
end as buyer_type
from aggregate_orders
)
select * from segment_users
```
nested query인 subquery로 표현하면 이렇게 되겠네요.
```
select
*,
case
when count_orders >= 3 then 'super_buyer'
when count_orders <3 and count_orders >= 2 then
'regular_buyer'
else 'single_buyer'
end as buyer_type
from (
select
customer_id,
count(order_id) as count_orders
from orders
where status not in ('returned', 'return pending')
group by 1
)
```
더 자세한 내용이 궁금하시면 아래 글을 보시면 좋습니다.
https://docs.getdbt.com/terms/cte