简体   繁体   中英

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.

Desired Output:

Notes | Total | Valid | Invalid | Consults Booked |

Total is count of all rows returned - already in the below query

Valid is any StatusID that is not 5 , 7 or 42

Invalid is the count of 5 , 7 and 42

Consults Booked is the count of 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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM