TSQL Pivot Long List of Columns(TSQL Pivot 长列列表)
问题描述
我希望使用数据透视函数将列的行值转换为单独的列.该列中有 100 多个不同的值,并且对数据透视函数的for"子句中的每个值进行硬编码将非常耗时,并且从可维护性的目的来看也不好.我想知道是否有更简单的方法来解决这个问题?
I am looking to use pivot function to convert row values of a column into separate columns. There are 100+ distinct values in that column and hard-coding each and every single value in the 'for' clause of the pivot function would be very time consuming and not good from maintainability purposes. I was wondering if there is any easier way to tackle this problem?
谢谢
推荐答案
您可以在 PIVOT 中使用动态 SQL 进行此类查询.动态 SQL 将获取您要在执行时转换的项目列表,从而无需对每个项目进行硬编码:
You can use Dynamic SQL in a PIVOT for this type of query. Dynamic SQL will get the list of the items that you want to transform on execution which prevents the need to hard-code each item:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.condition_id)
FROM t c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT memid, ' + @cols + ' from
(
select MemId, Condition_id, condition_result
from t
) x
pivot
(
sum(condition_result)
for condition_id in (' + @cols + ')
) p '
execute(@query)
参见 SQL Fiddle with Demo
如果您发布需要转换的数据样本,那么我可以调整我的查询来演示.
If you post a sample of data that you need to transform, then I can adjust my query to demonstrate.
这篇关于TSQL Pivot 长列列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:TSQL Pivot 长列列表
基础教程推荐
- 从字符串 TSQL 中获取数字 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
