PIVOT标题的第一列

时间:2019-07-29 16:11:33

标签: tsql

我有一个相当长的过程来创建一个表变量,该变量始终为13行,并且总是有19列。我知道每一列的名称和每一行的第一个变量。问题是我不知道如何旋转表格以便于将其轻松读出到网站。我必须逐行构建html表,但是客户端已经习惯了在顶部使用月份缩写。

这是带有[SELECT * FROM @TEMP]的表格的样子;

MonthName|Number_Screened|...|Tax_Credits_Earned|...|Year_To_Date_Tax_Credits_Earned
---------+---------------+---+------------------+---+-------------------------------
Jan      |159            |...|11030.26          |...|11030.26
Feb      |114            |...|6755.83           |...|17786.09
Mar      |107            |...|18250.73          |...|36036.82
Apr      |149            |...|11825.55          |...|47862.37
May      |117            |...|26149.78          |...|74012.15
Jun      |146            |...|11907.49          |...|85919.64
Jul      |104            |...|NULL              |...|85919.64
Aug      |NULL           |...|NULL              |...|85919.64
Sep      |NULL           |...|NULL              |...|85919.64
Oct      |NULL           |...|NULL              |...|85919.64
Nov      |NULL           |...|NULL              |...|85919.64
Dec      |NULL           |...|NULL              |...|85919.64
Total    |896            |...|85919.64          |...|85919.64

月份和总计将始终显示,并且将始终按照该顺序显示,因为临时表是按此顺序构造的,并逐行循环。

这就是我想要的样子;

                               |Jan     |Feb     |Mar     |...|Total
-------------------------------+--------+--------+--------+---+--------
Number_Screened                |159     |114     |107     |...|896
...                            |...     |...     |...     |...|...
Tax_Credits_Earned             |11030.26|6755.83 |18250.73|...|85919.64 
...                            |...     |...     |...     |...|...
Year_To_Date_Tax_Credits_Earned|11030.26|17786.09|36036.82|...|85919.64

我以前从未成功使用过数据透视。

1 个答案:

答案 0 :(得分:2)

您似乎想先取消数据,然后再取消PIVOT

示例

Select *
 From  (
        Select A.MonthName 
              ,B.*
         From  @Temp A
         Cross Apply ( values (1,'Number_Screened'   ,[Number_Screened])
                             ,(2,'Tax_Credits_Earned',[Tax_Credits_Earned])
                             ,(3,'Year_To_Date_Tax_Credits_Earned',[Year_To_Date_Tax_Credits_Earned])
                     ) B(Seq,Item,Value)
       ) src
 Pivot (sum(Value) for MonthName in ([Jan],[Feb],[Mar],[Apr],[May],[Jun],[Jul],[Aug],[Sep],[Oct],[Nov],[Dec],[Total]) ) pvt
 Order By Seq

返回

enter image description here