1

我有一张这样的桌子:

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

只是不知道该怎么做。谢谢。

4

3 回答 3

2

尝试枢轴

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


SQL 小提琴演示

于 2012-09-07T11:36:38.730 回答
0

您可以使用PIVOTor获得这样的结果,如果您在列GROUP 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并且您事先不知道它们,请使用 dynamic 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
于 2012-09-07T11:34:38.203 回答
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

如果那不能给您确切的答案,请尝试计数(不同的情况....):)

于 2012-09-07T11:36:45.780 回答