TSQL pivot with multiple column headers(具有多个列标题的 TSQL 数据透视表)
问题描述
我有一个带有动态列标题的 sql server 数据透视查询,结果如下
I have a sql server pivot query with dynamic column headers that results in something like the below
| DATE | Key1 | Key2 | Key 3 | Key4 |
|--------|---------------|---------------|-------------------|-----------|
| 1 | 1 | 2 | 3 | 4 |
| 2 | 1.29400 | 0.33840 | 0.04270 | (null) |
| 3 | 60.00000 | 70.00000 | 50.00000 | 180.00000 |
我的key"列标题字段具有子键,因此 key1 和 key2 可以具有相同的子键,我想像下面一样返回我的数据透视,以便我有多个列标题:
My 'key' column header field has subkeys so that key1 and key2 can have the same subkey, I would like to return my pivot like the below so that I have multiple column headers:
| DATE | Key1 | Key2 | Key 3 | Key4 |
|--------|---------------|---------------|-------------------|-----------|
| | subkey1 | subkey2 | subkey3 | subKey4|
|--------|---------------|---------------|-------------------|-----------|
| 1 | 1 | 2 | 3 | 4 |
| 2 | 1.29400 | 0.33840 | 0.04270 | (null) |
| 3 | 60.00000 | 70.00000 | 50.00000 | 180.00000 |
我目前的代码简化如下:
My current code is simplified as below:
DECLARE @cols AS NVARCHAR(MAX)
DECLARE @query AS NVARCHAR(MAX)
SELECT key, subkey, value into #temp from table
SELECT @cols = STUFF((SELECT ',' + QUOTENAME([key])
FROM #temp
GROUP BY [Key]
ORDER BY [Key]
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT [date], ' + @cols + ' from
(
select [key], [date], value
from #temp
) x
pivot
(
sum(value)
for [key] in (' + @cols + ')
) p
ORDER BY [Date] asc'
execute(@query)
是否可以在 sql 中像这样堆叠我的列标题?在 excel 中,这类似于将多个数据透视字段添加到列"区域
Is it possible to stack my column headers like this in sql? In excel this would be akin to adding multiple pivot fields into the 'Columns' area
推荐答案
您不能像在 excel 中那样有多个标题,但您可以改为预先连接标题.浏览器
You can't have multiple headers as you would in excel but you can pre-concatenate your headers instead. IE
SELECT key+'-'+subkey as key, value into #temp from table
这篇关于具有多个列标题的 TSQL 数据透视表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:具有多个列标题的 TSQL 数据透视表
基础教程推荐
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 无法解决整理冲突 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
