如何在sql中对多个列进行分组

时间:2015-03-08 10:42:58

标签: mysql sql

我的表格如下所示,

ID  EMP_ID  AMOUNT  MODE
1   E01     1000    CASH
2   E01     2000    CASH
3   E01     3000    DD
4   E01     1000    DD
5   E02     1500    CASH
6   E02     2000    DD

我想总结每个Emp支付的总金额以及根据MODE支付的金额总和。 例如,我希望结果为'7000'为totalAmount,'3000'为现金,'4000'为DD为E01。

我尝试了以下查询,但无法获得上述结果。

select sum(AMOUNT) as totalAmount from fees where EMP_ID = 'E01' group by mop

有人可以建议查询以获得上述结果吗?

编辑:

我想要结果表如下,

    ID  EMP_ID  TOTAL_AMOUNT    CASH_AMOUNT     DD_AMOUNT
    1   E01     7000            3000            4000
    2   E02     3500            1500            2000

2 个答案:

答案 0 :(得分:2)

用例到SUM cash / dd:

select EMP_ID,
       sum(AMOUNT) as totalAmount,
       sum(case when MODE = 'CASH' then AMOUNT else 0 end) as CASH_AMOUNT,
       sum(case when MODE = 'DD' then AMOUNT else 0 end) as DD_AMOUNT
from fees
group by EMP_ID

答案 1 :(得分:1)

将SUM函数与IF函数结合使用:

   SELECT EMP_ID,
          SUM(amount) AS TOTA_AMOUNT, 
          SUM(IF(`mode` = 'CASH', amount, 0)) AS CASH_AMOUNT,
          SUM(IF(`mode` = 'DD', amount, 0)) AS DD_AMOUNT
     FROM fees
 GROUP BY emp_id

SQL小提琴:http://www.sqlfiddle.com/#!9/94a55/1