프로그래밍/SQL, Hive, SAS 관련 정보

[SQL 기초] CTE와 Sub-query의 차이

물박사의 저장공간 2025. 4. 13. 15:46

2025.02.24 - [프로그래밍/SQL, Hive, SAS 관련 정보] - [SQL] Table of Contents


CTE는 쿼리 전체에서 재사용이 가능하며, 서브쿼리 내부에서도 참조할 수 있습니다.

select user_id from  
    (select user_id, count(movie_id) cnt
     from MovieRating
     group by user_id) t
where cnt = (select max(t.cnt) from t);

 

는 작동하지 않지만

 

with temp as 
    (select user_id, count(movie_id) cnt
     from MovieRating
     group by user_id)
select user_id 
from temp   
where cnt = (select max(cnt) from temp);

 

는 잘 작동하는 이유입니다.