MySQL查询获取列的总和

时间:2014-12-30 11:38:43

标签: mysql sql select group-by sum

我需要得到两个条件的列的总和.i.e

示例:

Dos        Insurance   bill_amount
29/11/14    LIC        200
29/11/14    Medicare        300
29/11/14    Selfpay        300
29/11/14    Medicare        400
29/11/14    aetna        900
29/11/14    selfpay       900
29/11/14    Prestige        100
29/11/14    LIC        500

我需要编写查询,以便我将视图作为

dos      Total_amount selfpay

29/11/14 2400           1200

请指导我查询

1 个答案:

答案 0 :(得分:3)

试试这个:

SELECT Dos, 
       SUM(CASE WHEN Insurance != 'Selfpay' THEN bill_amount ELSE 0 END) Total_amount, 
       SUM(CASE WHEN Insurance = 'Selfpay' THEN bill_amount ELSE 0 END) selfpay 
FROM tableA 
GROUP BY Dos;