首页 > 解决方案 > 是否可以在 TSQL 中有 2 个嵌套的枢轴函数

问题描述

我正在使用 TSQL 代码进行格式化。我想也许我可以使用 PIVOT 函数(sql 2012)实现我想要的,但我认为我需要在同一个查询中嵌套 2 个 Pivot,我不确定这是否可能。

我的表如下所示:原始数据 ,理想情况下,我想导出为 .csv 格式,如下所示Formatted output .csv file

我尝试使用带有以下代码的数据透视表`select * from (select distinct monthnum ,monthname -- ,Urban_rural ,performance ,Jurisdiction

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?)

干杯!

标签: csvtsqlformattingpivot-tablessis-2012

解决方案


Lakta 建议在 Unions 中使用数据透视表返回了我正在寻找的结果。

坦率地说,我不建议嵌套枢轴。您可以做的是制作一个暂存表(ex temporal 或 cte),您可以在其中“预先聚合”您的值,使它们具有一个通用的可旋转键:North_UrbanNorth_RuralNorth_All等。这很容易做到喜欢:

SELECT monthnum,
       monthname,
       Urban_rural + '_' + Jurisdiction Urban_rural_Jurisdiction
FROM ##cte union select monthnum, monthname, Urban_rural + '_All' Urban_rural_Jurisdiction from ##cte

推荐阅读