按ID返回列中的一组值计数

时间:2012-09-07 11:20:50

标签: sql-server-2008 pivot-table

我有一张这样的表:

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

无法解决如何做到这一点。感谢。

3 个答案:

答案 0 :(得分: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

答案 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 ('+@cols+')
) 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 :(得分: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

如果那不能给你确切的答案,那么试试count(不同的情况......):)