SQL Server - PIVOT分组

时间:2017-03-29 18:06:15

标签: sql-server tsql

在每个EmployeeID的分组中使用pivot时,我有这个令人困惑的事情。

SELECT *
FROM(
    SELECT  LoanAmount, lt.LoanTypeID
    FROM LoanContract lc
        INNER JOIN LoanType lt ON lt.LoanTypeID = lc.LoanTypeID
    GROUP BY EmployeeID, LoanAmount, lt.LoanTypeID
)src
PIVOT(
    SUM(LoanAmount)
    FOR LoanTypeID IN ([1], [2], [3], [4],  [5])
)piv;

有2个employeeID,其中emp = 1具有与lt.LoanTypeID = 5相关联的总和(lt.LoanAmount),另一方面,emp2具有与lt.LoanTypeID相关联的总和(lt.LoanAmount) 1和2

结果(1)显示:

[1]         [2]        [3]     [4]      [5]    
2400.00 30000.00    NULL    NULL    105000.00

预期结果(2):

[1]         [2]        [3]     [4]      [5]  
NULL         NULL       NULL    NULL     105000.00
2400.00      30000.00   NULL    NULL     NULL

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:3)

尝试在子查询中选择employeeId:

select *
from (
    select employeeID, -- here
        LoanAmount,
        lt.LoanTypeID
    from LoanContract lc
    inner join LoanType lt on lt.LoanTypeID = lc.LoanTypeID
    group by EmployeeID,
        LoanAmount,
        lt.LoanTypeID
    ) src
PIVOT(
    SUM(LoanAmount) 
    for LoanTypeID in ([1], [2], [3], [4], [5])
    ) piv;