데이터 엔지니어링/SQL

[SQL] 그룹별로 상위 n 개 구하기

허니비 honeybee 2023. 3. 10. 16:54

union 을 쓰는 방법도 있지만 rank 가 가장 직관적인 듯 하다 

 

chatbot_name 별로 sum_heart_price가 가장 높은 유저 5개를 고를 것임 

 

  • 편의를 위해 먼저 FROM 절을 이용해 heart_price 의 합계별로 랭킹이 계산된 ranked_data 를 생성한 뒤
  • SELECT 절을 이용해 출력에 필요한 것들을 선택해 주고
  • 5개 출력 랭킹 조건을 추가합니다

 

SELECT chatbot_name, user_seq, sum_heart_price, rank
FROM (
    SELECT 
        chatbot_name, 
        user_seq, 
        SUM(heart_price) AS sum_heart_price, 
        RANK() OVER (PARTITION BY chatbot_name ORDER BY SUM(heart_price) DESC) AS rank
    FROM hellobot_chatbot_data
    JOIN hellobot_chatbot_sales
    ON hellobot_chatbot_data.chatbot_seq = hellobot_chatbot_sales.chatbot_seq
    GROUP BY chatbot_name, user_seq
) ranked_data
WHERE rank <= 3
ORDER BY chatbot_name, rank

 

 

SELECT 절에서 rank 작업을 하면 리소스가 더 많이 들어가기 때문에 미리 만든 후 선택하고 조건거는 방법 이용. 이게 어렵다면 이렇게 할 수도 있음 

 

 

SELECT 
    chatbot_name, 
    user_seq, 
    SUM(heart_price) AS sum_heart_price, 
    RANK() OVER (PARTITION BY chatbot_name ORDER BY SUM(heart_price) DESC) AS rank
FROM hellobot_chatbot_data
JOIN hellobot_chatbot_sales
ON hellobot_chatbot_data.chatbot_seq = hellobot_chatbot_sales.chatbot_seq
GROUP BY chatbot_name, user_seq
HAVING rank <= 5
ORDER BY chatbot_name, rank
728x90