Sql查询动态表的Transpose

时间:2015-10-20 10:56:29

标签: sql sql-server database sql-server-2008 pivot

sql表如下,

    Name    Salary   NoticePeriod   CTC
    Jack     1520       15          123
    Bruce    1423       35          165 

它包含大约1000行。

我需要对此表进行转置,以使预期的输出为

    Fields           Jack     Bruce   Mike ..... Sam
    Salary           1520     1423    235   ..   561
    NoticePeriod      15       35      23        253 
    CTC               123      165     45   ...  125

我尝试在Sql Server 2008中使用Pivot和Unpivot功能。但由于Name记录很大,Pivot查询没有帮助。

我的sql尝试如下,

SELECT *
FROM (
  SELECT NAME,
    Salary,
    NoticePeriod,
    CTC
  FROM CTCTABLE WITH (NOLOCK)
  ) AS queryTable
UNPIVOT(Value FOR NAME IN (NAME, Salary, NoticePeriod, CTC)) AS unpv
PIvot(max(Value) FOR NAME IN (Salary, NoticePeriod, CTC)) pv

1 个答案:

答案 0 :(得分:2)

在您的情况下,您应该将列Salary, NoticePeriod, CTC展开成行,然后PIVOT

WITH Unpivoted
AS
(
    SELECT Name, Fields, SalaryValue
    FROM salaries AS s
    UNPIVOT
    (
      SalaryValue
      FOR  Fields IN(Salary, NoticePeriod, CTC)
    ) AS u
)
SELECT Fields, jack,bruce
FROM Unpivoted AS u
PIVOT
(
  MAX(SalaryValue)
  FOR Name IN(Jack, Bruce)
) AS p;

UNPIVOT会将列Salary, NoticePeriod, CTC转换为值:

enter image description here

然后,pivot将为每个字段值旋转工资值,并将名称转换为列。

当然,你必须动态地做,而不是像这样编写名单:

DECLARE @cols AS NVARCHAR(MAX);
DECLARE @colnames AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);

SELECT @cols = STUFF((SELECT distinct ',' +
                        QUOTENAME(name)
                       FROM salaries
                      FOR XML PATH(''), TYPE
                     ).value('.', 'NVARCHAR(MAX)') 
                        , 1, 1, '');


SELECT @query = 'WITH Unpivoted
                AS
                (
                    SELECT Name, Fields, SalaryValue
                    FROM salaries AS s
                    UNPIVOT
                    (
                        SalaryValue
                        FOR  Fields IN(Salary, NoticePeriod, CTC)
                    ) AS u
                )
                SELECT Fields, ' + @cols + '
                FROM Unpivoted AS u
                PIVOT
                (
                    MAX(SalaryValue)
                    FOR Name IN(' + @cols + ')' +
                ') p';

execute(@query);

这会给你:

enter image description here