是否可以在 SQL 中有 2 个嵌套的数据透视函数
is it possible to have 2 nested pivot functions in TSQL
我正在与使用 TSQL 代码进行格式化作斗争。我想也许我可以使用 PIVOT 函数(sql 2012)实现我想要的,但我想我需要在同一个查询中嵌套 2 个 Pivots,我不确定这是否可能。
我的 table 看起来像这样:Raw data
理想情况下,我想导出为这样的 .csv 格式 Formatted output .csv file
我试过使用带有以下代码的枢轴`select *
从
(
select 不同
月号
,月名
-- ,Urban_rural
,表现
,管辖权
from ##cte
)as src
pivot
(
avg(performance)
for jurisdiction in ([North],[south],[east],[west])
)piv;` but its only partly getting me where I wanted to be. [Pivot results][3]. So the questions I have are: How do i get my output file to look like the sample using SSIS or TSQL. Can you nest Pivot functions (or should you?)
干杯!
Lakta 关于在 Unions 中使用枢轴 table 的建议返回了我正在寻找的结果。
To be frank, I would not recommend nesting the pivots. What you could do is making a staging table (ex temporal or cte) in which you "pre-aggregate" your values in such a way, that they have a common pivot-able key: North_Urban
, North_Rural
, North_All
, etc. That can easily be done like:
SELECT monthnum,
monthname,
Urban_rural + '_' + Jurisdiction Urban_rural_Jurisdiction
FROM ##cte union select monthnum, monthname, Urban_rural + '_All' Urban_rural_Jurisdiction from ##cte
我正在与使用 TSQL 代码进行格式化作斗争。我想也许我可以使用 PIVOT 函数(sql 2012)实现我想要的,但我想我需要在同一个查询中嵌套 2 个 Pivots,我不确定这是否可能。
我的 table 看起来像这样:Raw data 理想情况下,我想导出为这样的 .csv 格式 Formatted output .csv file
我试过使用带有以下代码的枢轴`select * 从 ( select 不同 月号 ,月名 -- ,Urban_rural ,表现 ,管辖权
from ##cte
)as src
pivot
(
avg(performance)
for jurisdiction in ([North],[south],[east],[west])
)piv;` but its only partly getting me where I wanted to be. [Pivot results][3]. So the questions I have are: How do i get my output file to look like the sample using SSIS or TSQL. Can you nest Pivot functions (or should you?)
干杯!
Lakta 关于在 Unions 中使用枢轴 table 的建议返回了我正在寻找的结果。
To be frank, I would not recommend nesting the pivots. What you could do is making a staging table (ex temporal or cte) in which you "pre-aggregate" your values in such a way, that they have a common pivot-able key:
North_Urban
,North_Rural
,North_All
, etc. That can easily be done like:
SELECT monthnum,
monthname,
Urban_rural + '_' + Jurisdiction Urban_rural_Jurisdiction
FROM ##cte union select monthnum, monthname, Urban_rural + '_All' Urban_rural_Jurisdiction from ##cte