我有下面的表:SQL查詢獲得計數分組的項目
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
我有下面的表:SQL查詢獲得計數分組的項目
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
你可以嘗試這樣的事情
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
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
作爲旁觀者的替代選擇(好)解決方案:
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)或更糟(子選擇)或等於(更好兩種情況下的最佳執行計劃)。
+1不使用臨時表 – 2009-12-03 13:59:11
謝謝。 :-)然而,儘管我對upvote感到高興,但我應該澄清一下,旁觀者的解決方案不需要*臨時表;他只是用它來重新創建問題的原始表格並說明他的解決方案。 – Heinzi 2009-12-03 15:19:45
我之前觀察過的好點,但是我發現對於真正的新SQL開發人員來說,這可能會令人困惑,而不是一個巨大的事情。 – 2009-12-04 15:21:43
你可以這樣做......可能不是最優雅的,但它的工作... 剛換出@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
這是新的方式(因爲SQL Server 2005中),以解決用PIVOT功能問題:
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
我不使用這個我自己很多時候由於更復雜的語法,但也許有一些性能來獲取?
喜歡這個答案(比我輸入的要好)。表格的基本設計對我來說並不是很順利(它似乎沒有主鍵,非規範化爲地獄),應該可能改變。 – Romain 2009-12-03 13:31:02