我有一个带有动态列标题的sql server pivot查询,导致类似下面的内容
| 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可以有相同的子键,我想像下面一样返回我的数据库,这样我就有多个列标题:
| 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 |
我目前的代码简化如下:
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中,这类似于在“列”区域中添加多个透视字段
答案 0 :(得分:1)
您不能像在Excel中那样拥有多个标头,但您可以预先连接标头。 IE
SELECT key+'-'+subkey as key, value into #temp from table