用if语句汇总mysql

时间:2011-11-03 08:18:48

标签: mysql if-statement sum

我有以下查询:

SELECT BaDebet2 - BaCredit2 AS TOTAL FROM balansen

修改

我只想在TOTAL大于0时总结所有BaDebet2记录

3 个答案:

答案 0 :(得分:0)

这就是你想要的,对吧?

SELECT SUM(BaDebet2 - BaCredit2) AS TOTAL, IF(SUM(BaDebet2 - BaCredit2) > 0, SUM(BaDebet2 - BaCredit2) + BaDebet2, NULL) FROM balansen

如果TOTAL> 0您在第二列中有BaDebet2 + TOTAL,否则您将获得NULL。

答案 1 :(得分:0)

试试这个:

SELECT 
    CASE WHEN SUM(BaDebet2 - BaCredit2)>0 
         THEN SUM(BaDebet2 - BaCredit2) + BaDebet2 
    ELSE SUM(BaDebet2 - BaCredit2) END AS TOTAL
FROM balansen

答案 2 :(得分:0)

我认为这将解决您的问题。如果BaDebet2 - BaCredit2> 0,第二个查询将传递BaDebet2,否则为0.

SELECT SUM(BaDebet2_Actual) FROM 
(SELECT IF(BaDebet2 - BaCredit2>0, BaDebet2 ,0) AS BaDebet2_Actual 
 FROM balansen) A;