SQL - SUM OVER /@ - accumulated column

https://popsql.com/learn-sql/mysql/how-to-calculate-cumulative-sum-running-total-in-mysql


Use @

Select t0.person_name
FROM
(SELECT turn , person_id , person_name , weight ,
(@csum := @csum + weight) as cumulative_weight
FROM Queue ,(SELECT @csum := 0) r
order by turn) as t0
WHERE 
cumulative_weight <= 1000
ORDER BY cumulative_weight  DESC 

LIMIT 1 


Use Over

with CTE as (
Select person_id, person_name, weight, turn, sum(weight) over (order by turn) as Total_weight
from Queue
)
Select person_name
from CTE
where total_weight<=1000
order by total_weight DESC
limit 1


Use Math!!
SELECT q1.person_name
FROM Queue q1, Queue q2
WHERE q1.turn >= q2.turn
GROUP BY q1.turn
HAVING SUM(q2.weight) <= 1000
ORDER BY SUM(q2.weight) DESC
LIMIT 1

Input: 
Queue table:
+-----------+-------------+--------+------+
| person_id | person_name | weight | turn |
+-----------+-------------+--------+------+
| 5         | Alice       | 250    | 1    |
| 4         | Bob         | 175    | 5    |
| 3         | Alex        | 350    | 2    |
| 6         | John Cena   | 400    | 3    |
| 1         | Winston     | 500    | 6    |
| 2         | Marie       | 200    | 4    |
+-----------+-------------+--------+------+
Output: 
+-------------+
| person_name |
+-------------+
| John Cena   |
+-------------+
Explanation: The folowing table is ordered by the turn for simplicity.
+------+----+-----------+--------+--------------+
| Turn | ID | Name      | Weight | Total Weight |
+------+----+-----------+--------+--------------+
| 1    | 5  | Alice     | 250    | 250          |
| 2    | 3  | Alex      | 350    | 600          |
| 3    | 6  | John Cena | 400    | 1000         | (last person to board)
| 4    | 2  | Marie     | 200    | 1200         | (cannot board)
| 5    | 4  | Bob       | 175    | ___          |
| 6    | 1  | Winston   | 500    | ___          |
+------+----+-----------+--------+--------------+

留言

此網誌的熱門文章

MAP - Sort with stream

JAVA - DSF Example