如何写Pivot

时间:2014-03-04 07:18:35

标签: sql-server-2008 pivot-table

我有一个日期列的表格,如

DEPT_NAME   EMP_NAME    DESIGNATION DAY FIRST_SHIFT SECOND_SHIFT    THIRD_SHIFT GENERAL_SHIFT
C & I   DHAS YOGESH BABASAHEB   Diploma - Sr. Technician    01-3-13 0   0   0   0
C & I   DHAS YOGESH BABASAHEB   Diploma - Sr. Technician    02-3-13 0   0   0   0
C & I   DHAS YOGESH BABASAHEB   Diploma - Sr. Technician    03-3-13 0   0   0   0

我想

DEPT_NAME      EMP_NAME DESIGNATION 01-03-13                02-03-13    03-03-13


C & I   DHAS YOGESH BABASAHEB   Diploma - Sr. Technician 0 0 0 0     0 0 0 0     0 0 0 0

请帮帮我...... !!!

1 个答案:

答案 0 :(得分:0)

也许这会有所帮助:

首先是一些测试数据:

CREATE TABLE tbl
(
    DEPT_NAME VARCHAR(200),
    EMP_NAME VARCHAR(200),
    DESIGNATION VARCHAR(200),
    [DAY] DATE,
    FIRST_SHIFT INT,
    SECOND_SHIFT INT,
    THIRD_SHIFT INT,
    GENERAL_SHIFT INT
)
INSERT INTO tbl
VALUES
('C & I','DHAS YOGESH BABASAHEB','Diploma - Sr. Technician','01-3-13',0,0,0,0),
('C & I','DHAS YOGESH BABASAHEB','Diploma - Sr. Technician','02-3-13',0,0,0,0),
('C & I','DHAS YOGESH BABASAHEB','Diploma - Sr. Technician','03-3-13',0,0,0,0)

汇总唯一列:

DECLARE @cols VARCHAR(MAX)
;WITH CTE
AS
(
    SELECT
        ROW_NUMBER() OVER(PARTITION BY tbl.[DAY] ORDER BY tbl.[DAY]) AS rowNbr,
        tbl.[DAY]
    FROM
        tbl
)
SELECT @cols=STUFF
(
    (
        SELECT
            ',' +QUOTENAME([DAY])
        FROM
            CTE
        WHERE
            CTE.rowNbr=1
        FOR XML PATH('')
    )
,1,1,'')

然后执行动态sql:

DECLARE @query NVARCHAR(4000)=
N'SELECT
    *
FROM
(
    SELECT
        tbl.DEPT_NAME,
        tbl.EMP_NAME,
        tbl.DESIGNATION,
        tbl.[DAY],
        (
            CAST(tbl.FIRST_SHIFT AS VARCHAR(10))+'' ''+
            CAST(tbl.SECOND_SHIFT AS VARCHAR(10))+'' ''+
            CAST(tbl.THIRD_SHIFT AS VARCHAR(10))+'' ''+
            CAST(tbl.GENERAL_SHIFT AS VARCHAR(10))
        ) AS SHIFT
    FROM
        tbl
) AS p
PIVOT
(
    MAX(SHIFT) FOR [DAY] IN('+@cols+')
) AS pvt'

EXECUTE(@query)

在我的情况下删除创建的表:

DROP TABLE tbl

输出将是:

DEPT_NAME    EMP_NAME                DESIGNATION               2013-01-03   2013-02-03    2013-03-03
C & I        DHAS YOGESH BABASAHEB   Diploma - Sr. Technician  0 0 0 0      0 0 0 0       0 0 0 0