SQL Pivot表因此选择列正在向下

时间:2014-07-07 14:28:07

标签: sql pivot-table

好的,所以我有一张看起来像这样的表:

Date      Table_1    Table_2    Table_3    ...    Table_20
20140706  23         11         54                78
20140705  45         65         65                9
20140704  21         53         32                56
20140703  98         22         21                21
...

我想做的事情是这样的:

Table    20140706    20140705    20140704    20140703
Table_1  23          45          21          98
Table_2  11          65          53          22
Table_3  54          65          32          21
...

我对数据透视表很新,我真的不确定哪里可以开始。由于在Pivot表文章中大多数时候你需要一个总和,或者一个地方来转动,不能确定整个枢轴场景是如何工作的。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

有人想知道,我通过使用组合变量来设置我想要报告的日期,从而达到了我想要的结果。有一堆unpivotpivot表来按照我需要的方式定位表。

这是我的代码:

declare @d1 varchar(10) = CAST(DATEADD(dd,-1,CAST(GETDATE() as Date)) as varchar(10))
declare @d2 varchar(10) = CAST(DATEADD(dd,-2,CAST(GETDATE() as Date)) as varchar(10))
declare @d3 varchar(10) = CAST(DATEADD(dd,-3,CAST(GETDATE() as Date)) as varchar(10))
declare @d4 varchar(10) = CAST(DATEADD(dd,-4,CAST(GETDATE() as Date)) as varchar(10))
declare @d5 varchar(10) = CAST(DATEADD(dd,-5,CAST(GETDATE() as Date)) as varchar(10))
declare @d6 varchar(10) = CAST(DATEADD(dd,-6,CAST(GETDATE() as Date)) as varchar(10))
declare @d7 varchar(10) = CAST(DATEADD(dd,-7,CAST(GETDATE() as Date)) as varchar(10))
declare @SQL varchar(8000)

SET @SQL =
'Select
    *
From
    (
    Select
        unpvt.[Table]
        ,unpvt.value
        ,unpvt.Date
    From
        ORIGINAL_TABLE
        unpivot (
            value
            for [Table] in (Table_1
                ,Table_2
                ,Table_3
                ,...
                ,Table_35
            )
        ) unpvt
    Where
        Date > cast(dateadd(dd,-8,getdate()) as date)
    ) ref
    pivot (sum(ref.value)
        for ref.Date in (
            [' + @d1 + ']
            ,[' + @d2 + ']
            ,[' + @d3 + ']
            ,[' + @d4 + ']
            ,[' + @d5 + ']
            ,[' + @d6 + ']
            ,[' + @d7 + ']
        )
    ) as pvt'

EXEC(@SQL)