简体   繁体   English

SQL - 如何计算一列中多次出现的值

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

I have a table that has a StatusID column that has many different possible values, what I am trying to do is produce a report in the following format that is able to produce a count of various criteria. 我有一个具有StatusID列的表,该列具有许多不同的可能值,我想要做的是生成以下格式的报告,该报告能够生成各种条件的计数。

Desired Output: 期望的输出:

Notes | Total | Valid | Invalid | Consults Booked |

Total is count of all rows returned - already in the below query Total是返回的所有行的计数 - 已在下面的查询中

Valid is any StatusID that is not 5 , 7 or 42 有效是任何StatusID不是5742

Invalid is the count of 5 , 7 and 42 无效是的计5742

Consults Booked is the count of 4 预约的咨询数是4

(Invalid + Valid should equal Total) (无效+有效应等于总计)

So far I can only manage to get the Total , I have no idea how to determine the other values using IF or anything else. 到目前为止,我只能设法得到Total ,我不知道如何使用IF或其他任何东西确定其他值。

Query so far 查询到目前为止

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'

You can use an aggregate function with a CASE to get the other columns: 您可以使用带有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