我有这个查询。对于作品表中的AWARDED(1)和NOT AWARDED(0)作品,它应返回Count。
Select Count(w.WorkID)as Total, w.IsAwarded, org.OrganizationName
From Works w
Inner Join MC_MemberShip.Membership.Organization org
ON org.OrganizationID= w.Organization_ID
where Convert(varchar(11), w.OpeningDate) >= Convert(varchar(11), @FromDate)
and Convert(varchar(11), w.OpeningDate) < DATEADD(day, 1, Convert(varchar(11), @ToDate))
and w.IsActive=1 and
ISNULL(w.IsAwarded,0)= 0 and w.Organization_ID= case when @OrgID= -1 then w.Organization_ID else @OrgID end
group by org.OrganizationName, w.IsAwarded
现在这个查询返回NOT AWARDED的总计数,即仅0,但我想在同一查询中返回AWARDED的计数。
Organization TotalAwardedWorks TotalNotAwardedWorks
Town 1 1 2
Town 2 44 33
答案 0 :(得分:2)
您的查询应如下所示:
select org.OrganizationName,
Count(*) as Total,
sum(case when w.IsAwarded = 0 or w.IsAwarded is null then 1 else 0 end) as TotalNotAward,
sum(case when w.IsAwarded = 1 then 0 else 1 end) as TotalAward
from Works w Inner Join
MC_MemberShip.Membership.Organization org
on org.OrganizationID = w.Organization_ID
where w.OpeningDate >= @FromDate and
w.OpeningDate < dateadd(day, 1, @ToDate) and
w.IsActive = 1 and
(w.Organization_ID = @OrgId or @OrgID= -1)
group by org.OrganizationName;
注意:
case
子句中使用where
。使用or
更清楚地表示逻辑。case
将条件置于聚合函数中来获得所需内容。