我有一个带有动态列标题的 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 数据透视表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
将每个子标记转换为具有多个分隔符的单列-SQLConverting Every Child Tags in to a Single Column with multiple Delimiters -SQL Server (3)(将每个子标记转换为具有多个分隔符的单列-SQ
如何从多个表创建视图?How can I create a view from more than one table?(如何从多个表创建视图?)
根据前一行内的计算值创建计算值Create calculated value based on calculated value inside previous row(根据前一行内的计算值创建计算值)
如何将表格的前两列堆叠成一列,但也仅将第三How do I stack the first two columns of a table into a single column, but also pair third column with the first column only?(如何将表格的前两列堆
递归 t-sql 查询Recursive t-sql query(递归 t-sql 查询)
将月份名称转换为日期/月份编号(问题和答案的组Convert Month Name to Date / Month Number (Combinations of Questions amp; Answers)(将月份名称转换为日期/月份编号(问题和答案的组合