簡體   English   中英

SQL - 如何計算一列中多次出現的值

[英]SQL - How to Count Multiple Occurrences of Values in One Column

我有一個具有StatusID列的表,該列具有許多不同的可能值,我想要做的是生成以下格式的報告,該報告能夠生成各種條件的計數。

期望的輸出:

Notes | Total | Valid | Invalid | Consults Booked |

Total是返回的所有行的計數 - 已在下面的查詢中

有效是任何StatusID不是5742

無效是的計5742

預約的咨詢數是4

(無效+有效應等於總計)

到目前為止,我只能設法得到Total ,我不知道如何使用IF或其他任何東西確定其他值。

查詢到目前為止

select notes, tLeadStatus.Status, tLeadStatus.StatusID,
       count(*) as Total from LeadManagement.dbo.tLead with (NOLOCK)
left join LeadManagement.dbo.tInternetLead on tLead.Leadid = tinternetlead.leadid
left join LeadManagement..tLeadStatus on tLeadStatus.StatusID = tLead.Status
where (CampaignID = '12327')
  and (registerdate >= '2013-03-01' and registerdate < '2013-04-01')
group by notes,tLeadStatus.StatusID,tLeadStatus.Status
SUM(CASE WHEN StatusID NOT IN (5, 7, 42) THEN 1 ELSE 0 END) AS Valid,
SUM(CASE WHEN StatusID IN (5, 7, 42) THEN 1 ELSE 0 END) AS Invalid,
SUM(CASE WHEN StatusId = 4 THEN 1 ELSE 0 END) AS 'Consults Booked'

您可以使用帶有CASE的聚合函數來獲取其他列:

select notes, 
  count(*) as Total,
  sum(case when tLeadStatus.StatusID not in (5, 7, 42) then 1 else 0 end) Valid,
  sum(case when tLeadStatus.StatusID  in (5, 7, 42) then 1 else 0 end) Invalid,
  sum(case when tLeadStatus.StatusID= 4 then 1 else 0 end) ConsultsBooked
from LeadManagement.dbo.tLead with (NOLOCK)
left join LeadManagement.dbo.tInternetLead 
  on   tLead.Leadid = tinternetlead.leadid
left join LeadManagement..tLeadStatus 
  on tLeadStatus.StatusID = tLead.Status
where (CampaignID = '12327')
  and (registerdate >= '2013-03-01' and registerdate < '2013-04-01')
group by notes

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM