Hai我必须根据 hr_temp_id 我的表格结构来计算表格中所有先前条目的时间
play_id | hr_temp_id | min_id |
29 | 43 | 00:00:10 |
30 | 43 | 00:02:00 |
31 | 43 | 00:00:10 |
32 | 44 | 00:00:10 |
33 | 44 | 00:03:15 |
我试过像
这样的东西select r.min_id, (select sum(r2.min_id) from ciam_playlist_template r2
where r2.min_id <= r.min_id) as cumesum from ciam_playlist_template r
where r.hr_temp_id=43
我的结果如
00:00:10 | 10
00:02:00 | 210
00:00:10 | 10
预期结果
00:00:10
00:02:10
00:02:20
00:00:10
00:03:25
任何建议?
答案 0 :(得分:4)
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(play_id SERIAL PRIMARY KEY
,hr_temp_id INT NOT NULL
,min_id TIME NOT NULL
);
INSERT INTO my_table VALUES
(29,43,'00:00:10'),
(30,43,'00:02:00'),
(31,43,'00:00:10'),
(32,44,'00:00:10'),
(33,44,'00:03:15');
SELECT x.*
, SEC_TO_TIME(SUM(TIME_TO_SEC(y.min_id))) running
FROM my_table x
JOIN my_table y
ON y.hr_temp_id = x.hr_temp_id
AND y.play_id <= x.play_id
GROUP
BY x.play_id;
+---------+------------+----------+----------+
| play_id | hr_temp_id | min_id | running |
+---------+------------+----------+----------+
| 29 | 43 | 00:00:10 | 00:00:10 |
| 30 | 43 | 00:02:00 | 00:02:10 |
| 31 | 43 | 00:00:10 | 00:02:20 |
| 32 | 44 | 00:00:10 | 00:00:10 |
| 33 | 44 | 00:03:15 | 00:03:25 |
+---------+------------+----------+----------+
...或...
SELECT x.*
, SEC_TO_TIME(CASE WHEN @prev = hr_temp_id THEN @i:= @i+TIME_TO_SEC(min_id) ELSE @i:=TIME_TO_SEC(min_id) END) running
, @prev := hr_temp_id prev
FROM my_table x
, (SELECT @prev:=null,@i:=0) vars
ORDER
BY hr_temp_id
, play_id;