我有一个包含StatusID
列的表,其中包含许多不同的可能值,我要做的是按以下格式生成一个能够生成各种条件计数的报告。
期望输出:
Notes | Total | Valid | Invalid | Consults Booked |
总计是返回的所有行的计数 - 已在下面的查询中
有效的StatusID
不是5
,7
或42
5
,7
和42
的数量无效
预订的咨询数是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
答案 0 :(得分:9)
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'
答案 1 :(得分:2)
您可以使用带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