2017-03-23 68 views
0

我需要選擇記錄,直到列的總數達到一個變量數。mysql-SELECT直到達到一個數字

我有一個作品,但不是100%的查詢。我也希望看到call_date,並且我希望計數按日期順序完成。

SELECT NULL AS inbound_duration, NULL AS total 
    FROM dual 
WHERE (@total := 0) 
UNION 
SELECT inbound_duration, @total := @total + inbound_duration AS total 
FROM `records` where calling_user = '1' and call_date LIKE '2016-05-%%' and @total < 5000 ORDER BY call_date 

http://sqlfiddle.com/#!9/2e74ff

回答

0

我想這(注意:你有兩行相同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 
0

ORDER BY子句不聯合查詢的內允許英寸 爲了擺脫這個問題,請像下面

SELECT inbound_duration,total FROM 
(  
SELECT NULL AS inbound_duration, NULL AS total,NULL AS call_date 
    FROM DUAL 
WHERE (@total := 0) 
UNION 
SELECT inbound_duration, @total := @total + inbound_duration AS total,call_Date 
FROM `records` 
WHERE calling_user = '1' AND call_date LIKE '2016-05-%%' AND @total < 5000 
)t 
ORDER BY call_date 
+0

感謝但這只是對結果排序我的意思是我需要的總和日期 – dev7

+0

編輯與期望的結果集你的問題的順序進行,這將是更好地得到理解 –

0

你並不需要一個union初始化您的變量。您可以使用例如

select * from (
    SELECT inbound_duration, @total := @total + inbound_duration AS total 
    FROM `records`, (select @total := 0) init 
    where calling_user = '1' and call_date LIKE '2016-05-%%' 
    ORDER BY call_date 
) subq 
where total-inbound_duration < 5000 
order by total; 

由於您的日期不是唯一的,你應該添加主鍵你內心order by,否則你可能會得到不穩定的結果:如對於< 6000,結果可能包括或不包括金額100,具體取決於order by call_date是否隨機放置在同一日期的2500行之前或之後。

相關問題