我想這(注意:你有兩行相同call_date
:我認爲取得的順序可以是不確定的,除非你以指定其他指標分析 - 前inbound_duration或一些其他字段):
# DROP TABLE records;
CREATE TABLE `records` (
`inbound_duration` varchar(5) COLLATE utf8_unicode_ci NOT NULL,
`call_date` datetime NOT NULL,
`calling_user` varchar(25) COLLATE utf8_unicode_ci NOT NULL
);
INSERT INTO records
(inbound_duration, call_date, calling_user)
VALUES
(100, '2016-05-05 00:00:00', 1),
(1000, '2016-05-01 00:00:00', 1),
(900, '2016-05-03 00:00:00', 1),
(1500, '2016-05-02 00:00:00', 1),
(2000, '2016-05-04 00:00:00', 1),
(2500, '2016-05-05 00:00:00', 1)
;
SELECT * FROM records ORDER BY call_date;
SELECT NULL AS call_date, NULL AS inbound_duration, NULL AS total
FROM dual
WHERE @total := 0
UNION ALL
SELECT call_date, inbound_duration, @total := @total + inbound_duration AS total
FROM (SELECT * FROM records ORDER BY call_date) C where calling_user = '1' and call_date LIKE '2016-05-%%' and @total < 5000
;
DROP TABLE records;
輸出:
inbound_duration call_date calling_user
1 1000 01.05.2016 00:00:00 1
2 1500 02.05.2016 00:00:00 1
3 900 03.05.2016 00:00:00 1
4 2000 04.05.2016 00:00:00 1
5 100 05.05.2016 00:00:00 1
6 2500 05.05.2016 00:00:00 1
call_date inbound_duration total
1 01.05.2016 00:00:00 1000 1000
2 02.05.2016 00:00:00 1500 2500
3 03.05.2016 00:00:00 900 3400
4 04.05.2016 00:00:00 2000 5400
感謝但這只是對結果排序我的意思是我需要的總和日期 – dev7
編輯與期望的結果集你的問題的順序進行,這將是更好地得到理解 –