3

我有一个表,其中有一StatusID列有许多不同的可能值,我想做的是生成一个以下格式的报告,该报告能够生成各种标准的计数。

期望的输出:

Notes | Total | Valid | Invalid | Consults Booked |

Total 是返回的所有行的计数 - 已经在下面的查询中

Valid 是任何StatusID不是5,742

的计数无效57并且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
4

2 回答 2

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'
于 2013-04-23T13:43:29.907 回答
2

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
于 2013-04-23T13:44:32.820 回答