选择唯一值作为列并计数或匹配特定列的每个唯一值

时间:2019-06-21 09:43:00

标签: sql sql-server

我有一个包含四列的表:printIdNameCampaignId

以下是示例:

+----+-----------+------------+------+
| Id |   NAME    | CampaignId | Type |
+----+-----------+------------+------+
|  1 | Campaign1 |         10 |    0 |
|  2 | Campaign2 |         11 |    0 |
|  3 | Campaign2 |         11 |    1 |
|  4 | Campaign2 |         11 |    2 |
|  5 | Campaign2 |         11 |    3 |
|  6 | Campaign3 |         12 |    1 |
|  7 | Campaign3 |         12 |    2 |
|  8 | Campaign3 |         12 |    2 |
|  9 | Campaign3 |         12 |    2 |
| 10 | Campaign4 |         13 |    0 |
| 11 | Campaign4 |         13 |    2 |
+----+-----------+------------+------+
Type

我需要一个查询来创建一个新表,该表将输出一行,其中包含DROP TABLE IF EXISTS #TMP; CREATE TABLE #TMP ( [Id] INT IDENTITY , [NAME] NVARCHAR(20), [CampaignId] INT, [Type] INT ); INSERT INTO #TMP ([Name], [CampaignId], [Type]) VALUES ('Campaign1', 10, 0), ('Campaign2', 11, 0), ('Campaign2', 11, 1), ('Campaign2', 11, 2), ('Campaign2', 11, 3), ('Campaign3', 12, 1), ('Campaign3', 12, 2), ('Campaign3', 12, 2), ('Campaign3', 12, 2), ('Campaign4', 13, 0), ('Campaign4', 13, 2) SELECT * FROM #TMP 中每个唯一值的NameCampaignId和列以及每个唯一值的对应计数Type

我不知道CampaignId列中的确切数字和可能的值。可能会有所不同。

样本数据集的预期结果是一个表

+-----------+------------+-------+-------+-------+-------+
|   Name    | CampaignId | Type0 | Type1 | Type2 | Type3 |
+-----------+------------+-------+-------+-------+-------+
| Campaign1 |         10 |     1 |     0 |     0 |     0 |
| Campaign2 |         11 |     1 |     1 |     1 |     1 |
| Campaign3 |         12 |     0 |     1 |     3 |     0 |
| Campaign4 |         13 |     1 |     0 |     1 |     0 |
+-----------+------------+-------+-------+-------+-------+

2 个答案:

答案 0 :(得分:0)

使用条件聚合

selecr name,CampaignId,sum(case when  type =0 then 1 else 0 end) as type0,
sum(case when  type =1 then 1 else 0 end) as type1,
sum(case when  type =2 then 1 else 0 end) as type2,
sum(case when  type =3 then 1 else 0 end) as type3 from #TMP
group by name,CampaignId

答案 1 :(得分:0)

尝试一下:

SELECT name,
       campaignid,
       Type0=sum(case when type= 0 then 1 else 0 END ) ,
       Type1=sum(case when type= 1 then 1 else 0 END ) ,
       Type2=sum(case when type= 2 then 1 else 0 END ) ,
       Type3=sum(case when type= 3 then 1 else 0 END ) 
       FROM #TMP
       group by name,campaignid