如何在单个case语句中求和两列

时间:2019-04-10 11:44:37

标签: sql sql-server

下面的查询返回2行,但实际上我只需要一行;

select Datename(month, m.CreatedDate) as [Ay], sum(case when h.Cinsiyet=1 then 1 else 0 end) as [Group1], sum(case when h.Cinsiyet=2 then 1 else 0 end) as [Group2] from Muayene.Muayene m with(nolock)
join Ortak.Hasta h with(nolock) on m.HastaTc = h.HastaTc
group by  h.Cinsiyet, Datename(month, m.CreatedDate)

结果:

MonthName Group1 Group2
April     4500   0
April     0      9000

预期结果:

MonthName Group1 Group2
April     4500   9000

我知道我可以用另一个select语句将查询包装起来,然后按月分组,然后对这些结果求和。。但是效率不高并且看起来很脏。

如何在不做出另一条sum语句的情况下骗取期望的结果?

1 个答案:

答案 0 :(得分:1)

修复GROUP BY

select Datename(month, m.CreatedDate) as [Ay],
       sum(case when h.Cinsiyet = 1 then 1 else 0 end) as [Group1],
       sum(case when h.Cinsiyet = 2 then 1 else 0 end) as [Group2]
from Muayene.Muayene m join
     Ortak.Hasta h 
     on m.HastaTc = h.HastaTc
group by Datename(month, m.CreatedDate);