2017-04-13 69 views
0

我有這個查詢。它應該從作品表中返回AWARDED(1)和NOT AWARDED(0)作品的計數。如何返回2列中的計數?

 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 

現在這個查詢返回的總計數不授予即0只,但我想在同一個查詢中獲得太多回報計數。

Organization TotalAwardedWorks TotalNotAwardedWorks 
Town 1    1      2 
Town 2    44      33 
+1

左對齊的SQL很難閱讀...... – jarlh

+0

添加一些示例表格數據和預期結果 - 以及格式化文本。 – jarlh

+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; 

注:

  • 不要轉換日期字符串進行比較。這是不正當的。
  • 通常,不鼓勵在where子句中使用case。該邏輯使用or更清楚地表示。
  • 您可以通過使用case將條件置於聚合函數中來獲得想要的結果。
+0

謝謝,但SUM部分應該看起來像這樣我猜 – Covert

+1

sum(w.IsAwarded = 1 then 1 else 0 end時的情況)TotalAwarded, sum(w.IsAwarded = 0或w.IsAwarded爲null的情況,然後是0 else 1結束)爲TotalNotAwarded – Covert