2012-09-07 84 views
1

返回一組值的計數的專欄中,我有一個這樣的表:通過ID

ID Type 
---------- 
1  sent 
1  sent 
1  open 
1  bounce 
1  click 
2  sent 
2  sent 
2  open 
2  open 
2  click 

我想要一個查詢返回這樣的結果:

ID sent open bounce click 
1  2  1  1   1 
2  2  2  0   1 

就不能研究如何去做。謝謝。

回答

0

您可以通過使用PIVOTGROUP BY得到這樣的結果,你甚至可以得到結果,如果你在Type列有變量值:

測試數據:

CREATE TABLE #t(ID INT, Type VARCHAR(100)) 
INSERT #t 
VALUES 
(1,  'sent'), 
(1,  'sent'), 
(1,  'open'), 
(1,  'bounce'), 
(1,  'click'), 
(2,  'sent'), 
(2,  'sent'), 
(2,  'open'), 
(2,  'open'), 
(2,  'click') 

PIVOT方法:

SELECT pvt.* 
FROM #t 
PIVOT 
(
    COUNT(Type) FOR Type IN ([sent], [open], [bounce], [click]) 
) pvt 

如果Type還有其他可能的值,並且您不知道它們提前使用動態PIVOT

DECLARE @cols NVARCHAR(1000) = STUFF(
(
    SELECT DISTINCT ',[' + Type + ']' 
    FROM #t 
    FOR  XML PATH('') 
), 1, 1, '') 

DECLARE @query NVARCHAR(2000) = 
' 
SELECT pvt.* 
FROM #t 
PIVOT 
(
    COUNT(Type) FOR Type IN ('[email protected]+') 
) pvt 
' 

EXEC(@query) 

如果你已經知道的固定值Type,你也可以使用:

SELECT ID, 
     COUNT(CASE WHEN Type = 'sent' THEN 1 END) [sent], 
     COUNT(CASE WHEN Type = 'open' THEN 1 END) [open], 
     COUNT(CASE WHEN Type = 'bounce' THEN 1 END) bounce, 
     COUNT(CASE WHEN Type = 'click' THEN 1 END) click 
FROM #t 
GROUP BY ID 
2

嘗試PIVOT

SELECT ID,[sent],[open],[bounce],[click] 
FROM your_table 
PIVOT (COUNT([Type]) 
FOR [Type] in ([sent],[open],[bounce],[click]))p 


SQL Fiddle Demo

0
Select Id, 
count(case When type='sent' then 1 else 0 end) as sent, 
count(case when type='open' then 1 else 0 end) as open 
From table 
Group by Id 

如果不會給你確切的答案,然後嘗試次數(不同的情況....):)