【问题标题】:Pivot row data and count into columns [duplicate]将行数据透视并计入列[重复]
【发布时间】:2021-10-18 03:05:54
【问题描述】:
我有如下两列数据:
| Client |
Type |
| A |
Pencil |
| A |
Ruler |
| A |
Pen |
| B |
Pencil |
| B |
Ruler |
| C |
Pencil |
| C |
Pen |
我想旋转“类型”并将它们设为列并按“客户”分组。结果如下所示:
| Client |
Count(Pencil) |
Count(Ruler) |
Count(Pen) |
| A |
1 |
1 |
1 |
| B |
1 |
1 |
0 |
| C |
1 |
0 |
1 |
如何在 SQL Server 上实现这一点?
谢谢
【问题讨论】:
标签:
sql
sql-server
tsql
pivot
【解决方案1】:
在 SQL Server 中,您可以将其表示为:
select client,
sum(case when type = 'Pencil' then 1 else 0 end) as pencil,
sum(case when type = 'Ruler' then 1 else 0 end) as ruler,
sum(case when type = 'Pen' then 1 else 0 end) as pen
from t
group by client;
【解决方案2】:
请参考MSDN。
SELECT Client, [Pencil], [Ruler], [Pen]
FROM
(
SELECT Client, Type
FROM tableName
) AS SourceTable
PIVOT
(
count(Type)
FOR Type IN ([Pencil], [Ruler], [Pen])
) AS PivotTable;