2014-11-03 72 views
0

我有問題與MySQL語法,我有表像MYSQL SUM,IF和結果爲0

GNT6988 rawabuaya 30000000 
GNT3429 Purwacaraka 100000 
GNT1326 CLARA  15000000 
GNT9059 bensugih1 6100000 
GNT9620 bensugih2 6100000 
GNT9851 Abdulfattah 500000 
GNT3927 SUKSES01 10000000 
GNT4469 SUKSES02 10000000 

和我有mysql語法像

SELECT trx, SUM(jmlgf) AS jumlahgf 
     FROM gf_start 
     GROUP BY trx 
     HAVING jumlahgf < 4000000 ORDER BY tgl ASC LIMIT 40 

我得到了導致

GNT3429 100000 
GNT9851 500000 
GNT1405 1000000 
GNT9660 100000 
GNT7222 100000 
GNT2407 2100000 
GNT3383 100000 
GNT5586 100000 
GNT1419 100000 

**i want to get result like** 

GNT3429 100000 
GNT9851 500000 
GNT1405 1000000 
GNT9660 0 
GNT7222 0 
GNT2407 0 
GNT3383 0 

如果SUM(jmlgf)> = 1600000

我應該如何處理mysql語法?

使用PHP MYSQL

+1

請檢查您的問題,我不確定你在問什麼。 – Haris 2014-11-03 15:05:18

+0

1)發佈表結構2)告訴我們你想從中計算出什麼3)通過在你的鍵盤上扔一隻貓命名錶字段不是一個好習慣。可以考慮動物濫用,結果是痛苦的閱讀。 – David162795 2014-11-03 15:11:56

+0

我想要得到的結果總數SUM(jmlgf)<=(名義)我的查詢停止讀取記錄。謝謝 – 2014-11-03 15:15:13

回答

1

無論我使用一個變量,像這樣: -

SELECT trx, @sum_so_far:[email protected]_so_far + jumlahgf, IF(@sum_so_far >= 1600000, 0, jumlahgf) AS jumlahgf 
FROM 
(
    SELECT trx, SUM(jmlgf) AS jumlahgf 
    FROM gf_start 
    GROUP BY trx 
    HAVING jumlahgf < 4000000 
    ORDER BY tgl ASC 
) sub0 
CROSS JOIN 
(
    SELECT @sum_so_far:=0 
) sub1 
LIMIT 40 

或參加與另一個查詢結果得到的總和,到目前爲止,這樣的事情: -

SELECT trx, IF(rolling_cnt >= 1600000, 0, SUM(jmlgf)) AS jumlahgf 
FROM gf_start 
(
    SELECT a.trx, SUM(b.jmlgf) AS rolling_cnt 
    FROM gf_start a 
    INNER JOIN gf_start b 
    ON a.trx = b.trx 
    AND a.tgl <= b.tgl 
    GROUP BY a.trx 
) sub0 
ON gf_start.trx = sub0.trx 
GROUP BY trx 
HAVING jumlahgf < 4000000 
ORDER BY tgl ASC 
LIMIT 40 
+0

啊太棒了,你救了我的現場..:D謝謝師父 – 2014-11-03 22:54:38