具有条件的两行的MySQL SUM

时间:2016-06-30 08:13:07

标签: mysql sql-server sum

我是MySQL的初学者,我需要你的帮助。 我有这样的事情:

ID  Project  Type  Amount
1   1        I     5000
2   1        D     1000
3   2        I     3500
4   3        I     4300
5   3        D     1200

我想要这样的东西(同一个项目的I类型和D类型的数量之间的差异; D类型并不总是存在):

Project  Amount
1        4000
2        3500
3        3100

2 个答案:

答案 0 :(得分:5)

我建议使用caseAmount+-一起使用:

  select Project as Project,
         sum(case  
               when Type = 'I' then
                 Amount
               when Type = 'D' then 
                -Amount 
             end case) as Amount
    from MyTable
group by Project
--    order by Project -- uncomment this if you want sorted cursor

答案 1 :(得分:1)

试试这个;)

select
    Project,
    sum(if(Type = 'I', Amount, -Amount)) as Amount
from table1
group by Project

SQLFiddle DEMO HERE