需要在sql server中创建动态pivot

时间:2017-05-19 06:11:14

标签: sql sql-server-2008 sql-server-2012

我有下面的查询运行正常,但它是一个静态的数据透视表。我想动态创建它。我想知道这段代码需要做哪些更改,以便我可以将其作为动态支点。 在此先感谢!!!!

select * from
    (
select g.NationalityName_1,DepartmentName_1,h.EmployeeID from HR_Department hr
            join
HR_EmploymentInformation h
    on h.DepartmentID=hr.DepartmentID
        join
HR_EmployeeDetail e
    on e.EmployeeID=h.EmployeeID
        join
GEN_Nationality g
    on g.NationalityID=e.DefaultNationalityID
) as fev
pivot 
(
    count(employeeId)
    for departmentname_1 in (Administration,Academia,[New Department 1],[New Department 2],[New Department 3],[New Department 5])
) as pvt

这是输出:

NationalityName_1   Administration  Academia    New Department 1    New Department 2    New Department 3    New Department 5
Algeria                 0            1          0                   0                   0                   0

这是上述查询的输出及其正确的问题,我面临的问题是如果我创建一个新部门,我必须再次更改我不想要的代码。

1 个答案:

答案 0 :(得分:0)

试试这个:我们可以通过以下方式编写动态PIVOT

DECLARE @col VARCHAR(1000)
DECLARE @sql VARCHAR(2000)

SELECT @col = COALESCE(@col + ', ','') + QUOTENAME(DepartmentName_1)
FROM HR_Department hr
JOIN HR_EmploymentInformation h ON h.DepartmentID = hr.DepartmentID
JOIN HR_EmployeeDetail e ON e.EmployeeID = h.EmployeeID
JOIN GEN_Nationality g ON g.NationalityID = e.DefaultNationalityID

SET @sql = '
    SELECT NationalityName_1, ' + @col + '
    FROM
        (SELECT g.NationalityName_1,
            DepartmentName_1,
            h.EmployeeID 
        FROM HR_Department hr
        JOIN HR_EmploymentInformation h ON h.DepartmentID = hr.DepartmentID
        JOIN HR_EmployeeDetail e ON e.EmployeeID = h.EmployeeID
        JOIN GEN_Nationality g ON g.NationalityID = e.DefaultNationalityID
        ) AS fev
    PIVOT 
    (
        COUNT(employeeId)
        FOR departmentname_1 IN ( ' + @col + ' )
    ) AS pvt'

EXEC (@sql)