SQL Server-将5个查询合并到一个表中
您好,我必须创建一份报告,说明药店的出境使用量 有4种类型的出站类型:SMS、呼叫、电子邮件和P 我想得到每种类型的总数以及每种药房的总数 以下是我目前的疑问SQL Server-将5个查询合并到一个表中,sql,sql-server,Sql,Sql Server,您好,我必须创建一份报告,说明药店的出境使用量 有4种类型的出站类型:SMS、呼叫、电子邮件和P 我想得到每种类型的总数以及每种药房的总数 以下是我目前的疑问 select PharmacyID, count(*) as total from OutboundCallData where datepart(year, DateReceived) = 2014 and datepart(month, datereceived) = 1 and (NotificationMode =
select PharmacyID, count(*) as total
from OutboundCallData
where datepart(year, DateReceived) = 2014 and datepart(month, datereceived) = 1
and (NotificationMode = 'sms' or NotificationMode = 'call' or NotificationMode = 'email' or NotificationMode = 'p')
group by PharmacyID
select PharmacyID, count(*) as sms
from OutboundCallData
where datepart(year, DateReceived) = 2014 and datepart(month, datereceived) = 1
and NotificationMode = 'sms'
group by PharmacyID
select PharmacyID, count(*) as call
from OutboundCallData
where datepart(year, DateReceived) = 2014 and datepart(month, datereceived) = 1
and NotificationMode = 'call'
group by PharmacyID
select PharmacyID, count(*) as email
from OutboundCallData
where datepart(year, DateReceived) = 2014 and datepart(month, datereceived) = 1
and NotificationMode = 'email'
group by PharmacyID
select PharmacyID, count(*) as p
from OutboundCallData
where datepart(year, DateReceived) = 2014 and datepart(month, datereceived) = 1
and NotificationMode = 'p'
group by PharmacyID
我想把所有这些合并成一张这样的表
PharmacyID| SMS | Call | Email | P | Total
-----------------------------------------
999000001 | 3 | 4 | 5 | 6 | 18
999000002 | 12 | 0 | 14 | 8 | 34
显示0或null就可以了。一个简单的交叉制表符可以:
select PharmacyID,
count(*) as total,
count(case when NotificationMode = 'sms' then 1 else null end) as sms,
count(case when NotificationMode = 'email' then 1 else null end) as email,
count(case when NotificationMode = 'call' then 1 else null end) as call,
count(case when NotificationMode = 'p' then 1 else null end) as p
from OutboundCallData
where datepart(year, DateReceived) = 2014 and datepart(month, datereceived) = 1
and (NotificationMode = 'sms' or NotificationMode = 'call' or NotificationMode = 'email' or NotificationMode = 'p')
group by PharmacyID
或者,您可以使用轴
:
SELECT PharmacyID, [sms], [email], [call], [p]
FROM
(SELECT PharmacyID, NotificationMode
from OutboundCallData) AS outboundData
PIVOT
(
count(NotificationMode )
FOR NotificationMode IN ([sms], [email], [call], [p])
) AS P
下面是一个使用PIVOT关键字的示例
SELECT PharmacyID, [sms], [email], [call], [p]
FROM
(SELECT PharmacyID, NotificationMode
from OutboundCallData
where datepart(year, DateReceived) = 2014 and datepart(month, datereceived) = 1) o
PIVOT
(
count(NotificationMode )
FOR NotificationMode IN ([sms], [email], [call], [p])
) AS [PivotTable]
这种技术称为交叉表。我个人更喜欢这个而不是一个支点。我发现它们更容易阅读,而且在性能上也略胜一筹d感谢您的帮助,我在关键字“PIVOT”附近遇到一个错误,语法不正确。这是由于在末尾使用了
PIVOT
作为表名。我现在已经补救了。