下面的查询返回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语句的情况下骗取期望的结果?
答案 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);