2

我想旋转并转动现有表格并生成报告(交叉表)。您会看到 vals 列由 date_a 和 date_e 列的唯一组合确定。我不知道该怎么做。

4

1 回答 1

1

像这样的东西:

测试数据

CREATE TABLE #tbl(date_a DATE,date_e DATE, vals FLOAT)

INSERT INTO #tbl
VALUES
    ('2/29/2012','1/1/2013',28.47),
    ('2/29/2012','2/1/2013',27.42),
    ('2/29/2012','3/1/2013',24.36),
    ('3/1/2012','1/1/2013',28.5),
    ('3/1/2012','2/1/2013',27.35),
    ('3/1/2012','3/1/2013',24.39),
    ('3/6/2012','1/1/2013',27.75),
    ('3/6/2012','2/1/2013',26.63),
    ('3/6/2012','3/1/2013',23.66)

询问

SELECT
    *
FROM
(   
    SELECT
        tbl.date_a,
        tbl.date_e,
        vals
    FROM
        #tbl AS tbl
) AS SourceTable
PIVOT
(
    SUM(vals)
    FOR date_e IN ([1/1/2013],[2/1/2013],[3/1/2013])
) AS pvt

DROP TABLE #tbl

编辑

如果你不知道有多少列,那么你需要做一个动态的pivot。像这样:

独特的列

DECLARE @cols VARCHAR(MAX)
;WITH CTE
AS
(
    SELECT
        ROW_NUMBER() OVER(PARTITION BY date_e ORDER BY date_e) AS RowNbr,
        tbl.*
    FROM
        #tbl AS tbl
)
SELECT @cols=STUFF
(
    (
        SELECT 
            ',' +QUOTENAME(date_e)
        FROM
            CTE
        WHERE
            CTE.RowNbr=1
        FOR XML PATH('')
    )
,1,1,'')

动态枢轴

DECLARE @query NVARCHAR(4000)=
N'SELECT
    *
FROM
(   
    SELECT
        tbl.date_a,
        tbl.date_e,
        vals
    FROM
        #tbl AS tbl
) AS SourceTable
PIVOT
(
    SUM(vals)
    FOR date_e IN ('+@cols+')
) AS pvt'
EXECUTE(@query)
于 2012-04-17T10:43:46.557 回答