2017-05-19 119 views
0

我有下面的查詢,它運行良好,但它的靜態數據透視表。我想動態創建它。我想知道這段代碼需要什麼修改,以便我可以把它變成動態的關鍵。 提前致謝!需要在sql server中創建動態數據透視表

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 

這是上面的查詢和正確的輸出,我面臨的問題是,如果我創建一個新的部門我不得不再次改變一個我不想要的代碼。

+0

編寫動態PIVOT如果我爲你提供動態的解決方案則可以應用在你的代碼?因爲沒有樣本數據和預期的產出,很難處理它。 – Susang

+0

是的,我可以運行查詢.. –

回答

0

試試這個:我們可以通過以下方式

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) 
+0

我試着你說的,但它給了我一個錯誤。我無法在評論中發佈我的查詢我不知道爲什麼 –

+0

更新,請檢查,如果它適合你。 – Susang

+0

消息105,級別15,狀態1,行15 字符串'Acad'後面未封閉的引號。 Msg 102,Level 15,State 1,Line 15 'Acad'附近語法不正確。它給出了一個錯誤 –