glog : cupucharm

[MySQL] 누적 합계 SUM OVER (LeetCode 1204) 본문

SQL

[MySQL] 누적 합계 SUM OVER (LeetCode 1204)

오이호박참외 2024. 10. 20. 12:00

☀️ SUM OVER

데이터 집계 및 분석을 위한 기능으로, 특정 조건에 따라 누적 합계를 계산할 수 있다. 데이터의 특정 그룹 내에서 합계를 계산하는데 유용하다.

  • SUM() 함수 : 특정 열의 값을 합산한다.
  • OVER() 절 : 집계 함수가 적용될 범위를 정의한다. 이 절을 사용하여 데이터의 특정 부분에 대해 집계할 수 있다.

🃏 예시 - 특정 날짜별로 누적 결제 금액을 계산한다.

orders 테이블

order_date gender amount
2024-01-01 Male 100
2024-01-02 Male 200
2024-01-01 Female 150
2024-01-03 Female 250

 

order_date에 따라 정렬된 amount의 누적합계를 계산한다.

SELECT
    order_date,
    SUM(amount) OVER (ORDER BY order_date) AS cumulative_amount
FROM orders;

 

결과

order_date cumulative_amount
2024-01-01 250
2024-01-02 450
2024-01-03 700

🎊 PARTITION BY와 함께 사용하기

  • PARTITION BY : 데이터를 특정 그룹으로 나누어 집계할 수 있다. 예를 들어, 성별이나 부서별로 누적 합계 등을 계산할 수 있다.
SELECT
    gender, order_date,
    SUM(amount) OVER (PARTITION BY gender ORDER BY order_date) AS cumulative_amount
FROM orders;

성별에 따라 그룹화된 후, 각 성별 내에서 날짜별로 누적 합계를 계산한다.

결과

order_date gender cumulative_amount
2024-01-01 Male 100
2024-01-02 Male 300
2024-01-01 Female 150
2024-01-03 Female 400

리트코드 LeetCode 1204

https://github.com/cupucharm/LeetCode/tree/main/1204-last-person-to-fit-in-the-bus

 

LeetCode/1204-last-person-to-fit-in-the-bus at main · cupucharm/LeetCode

Collection of LeetCode questions to ace the coding interview! - Created using [LeetHub v3](https://github.com/raphaelheinz/LeetHub-3.0) - cupucharm/LeetCode

github.com

https://leetcode.com/problems/last-person-to-fit-in-the-bus/?envType=study-plan-v2&envId=top-sql-50

SUM(weight) OVER (ORDER BY turn) as total_weight