sql - Pivot multiple rows in initial table
问题描述
I have a table which i would like to pivot to show how many categories a person is affiliated with...
I would like to pivot this to show:
There are a lot more members and categories but the theory i believe should be the same.
I have attempted this however it only shows the first line for each.
Thanks in advance
Will
解决方案
您只需要使用 PIVOT 函数中的 Number 字段求和,就可以获得一个类别列表:
DECLARE @categories AS NVARCHAR(MAX),
@your_query AS NVARCHAR(MAX);
select @categories = STUFF((SELECT distinct ',' + QUOTENAME(Category)
FROM your_table
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT RegNo, ' + @categories + ' from
(
SELECT RegNo, Category, Number FROM your_table) tab
PIVOT
(
SUM(Number)
FOR Category IN (' + @categories + ')
) p iv
ORDER BY piv.RegNo'
execute(@your_query)
推荐阅读
- python - 调用 keras 自定义指标进行预测
- sql-server - 罗马尼亚字符“ă”在 SQL Server 中等于“a”
- python - 如何使用多个列表执行计算?
- spring-boot - 由于多个感叹号,SpringBoot 无法从 Runnable jar 加载属性文件
- docker - 如何为以下命令创建 docker 文件
- go - gofpdf - 居中对齐文本之间的粗体文本
- javascript - 将 Angular 书面扩展迁移到清单 V3
- javascript - 我的 React 应用程序从不加载 localhost:3000 它只是一直在旋转(认为 React-Router-Dom 是问题所在)
- c - Openssl 1.1.1 库在自签名签名上出现错误
- python - 如何使用 RL 代码中的嵌套 if 向量化 for 循环?