我有一个包含以下列的表:
agent status
A Mail Sent
B Fax Sent
A Fax Sent
B Mail Sent
B Mail Sent
B Fax Sent
我想得到这个结果:
Agent Fax_Count Mail_Count
A 1 1
B 2 2
答案 0 :(得分:7)
您可以尝试这样的事情
DECLARE @TABLE TABLE(
agent VARCHAR(10),
status VARCHAR(10)
)
INSERT INTO @TABLE (agent,status) SELECT 'A','Mail Sent'
INSERT INTO @TABLE (agent,status) SELECT 'B','Fax Sent'
INSERT INTO @TABLE (agent,status) SELECT 'A','Fax Sent'
INSERT INTO @TABLE (agent,status) SELECT 'B','Mail Sent'
INSERT INTO @TABLE (agent,status) SELECT 'B','Mail Sent'
INSERT INTO @TABLE (agent,status) SELECT 'B','Fax Sent'
SELECT agent,
SUM(CASE WHEN status = 'Mail Sent' THEN 1 ELSE 0 END) Mail_Count ,
SUM(CASE WHEN status = 'Fax Sent' THEN 1 ELSE 0 END) Fax_Count
FROM @TABLE
GROUP BY agent
答案 1 :(得分:1)
作为旁观者(好)解决方案的替代方案:
SELECT agent,
(SELECT COUNT(*) FROM myTable WHERE agent = t.agent AND status = 'Mail Sent') Mail_Count,
(SELECT COUNT(*) FROM myTable WHERE agent = t.agent AND status = 'Fax Sent') Fax_Count
FROM myTable t
GROUP BY agent
根据数据的分布,性能可能优于他的解决方案(在计算字段上没有SUM)或更差(子选择)或相等(如果查询分析器在两种情况下都找到最佳执行计划)。
答案 2 :(得分:0)
select Name, SUM(MailSent),SUM(FaxSent)
from
(
select
case Status when 'Mail Sent' then 1 else 0 end as MailSent ,
case Status when 'Fax Sent' then 1 else 0 end as FaxSent ,
Name
from Agents
) tmp
答案 3 :(得分:0)
你可以做到这一点......可能不是最优雅的但它会起作用...... 只需将@Table换成你正在查询的表......
SELECT DISTINCT
T.AGENT,
(SELECT COUNT(AGENT) FROM @TABLE WHERE AGENT = T.AGENT AND Status LIKE 'Fax%') AS Fax_Count,
(SELECT COUNT(AGENT) FROM @TABLE WHERE AGENT = T.AGENT AND Status LIKE 'Mail%') AS Email_Count
FROM
@TABLE T
答案 4 :(得分:0)
这是使用PIVOT功能解决问题的新方法(自SQL Server 2005起):
SELECT agent, [Mail Sent] AS Mail_Count, [Fax Sent] AS Fax_Count
FROM
(
SELECT T.agent, T.status, COUNT(*) AS Counter
FROM tblAgents AS T
GROUP BY T.agent, T.status
) AS Data
PIVOT
(
SUM(Counter) FOR [status] IN ([Mail Sent], [Fax Sent])
) AS PivotTable
由于语法更复杂,我不经常使用这个,但也许有一些性能可以获得?