2017-07-17 23 views
0

我正在解決以下問題。當達到某個限制時,MySQL會獲得行

我們正在尋找一個查詢,當SUM(price_total)達到按類型分組的某個級別時,它將檢索數據。表的結構是如下:

CREATE TABLE `Table1` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `Date` datetime DEFAULT NULL, 
    `type` int(11) DEFAULT NULL, 
    `price_total` int(11) DEFAULT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1; 

數據

INSERT INTO `Table1` (`id`, `Date`, `type`, `price_total`) 
VALUES 
    (1,'2013-02-01 00:00:00',1,5), 
    (2,'2013-02-01 00:00:00',2,15), 
    (3,'2013-02-02 00:00:00',1,25), 
    (4,'2013-02-03 00:00:00',3,5), 
    (5,'2013-02-04 00:00:00',4,15), 
    (6,'2013-03-05 00:00:00',1,20), 
    (7,'2013-08-07 00:00:00',4,15); 

實施例的結果爲閾值15,按時間順序。

Type 1: 2013-02-02 00:00:00 Because here it came above 15. (15+5) 
Type 2: 2013-02-01 00:00:00 
Type 3: n/a SUM(price_total) < 15 
Type 4: 2013-02-04 00:00:00 

總結。我想知道他們越過門檻的日期。價格總額應按時間順序總結。

+0

你已經有什麼查詢? –

+0

SELECT \t類型, \t SUM(price_total) FROM \t表1 GROUP BY類型;聽起來很傻......(我不是一個愚蠢的MySQL用戶,但說實話,我不知道從哪裏開始)。實施一個無法工作,因爲我們也希望類型3出現。否則類型3將被過濾掉。 –

+0

所以你正在尋找第一時刻你的價值總和大於一定的門檻。 假設你有一個類型的3個值,5,10,12。這筆款項的順序是否重要? (5 + 12> 15,然而10 + 12也是大15) –

回答

0

這裏有一個簡單的,自我解釋查詢:

select type, min(date) as date 
from (
    select t1.type, t1.date, sum(t2.price_total) as total 
    from table1 t1 
    join table1 t2 
     on t2.type = t1.type 
     and t2.date <= t1.date 
    group by t1.type, t1.date 
    having total >= 15 
) sub 
group by type 

演示:http://rextester.com/GMAK8269

相關問題