使用pivot

时间:2018-05-28 04:09:41

标签: sql sql-server sql-server-2012 sql-server-2014 sql-server-2016

我想根据以下要求使用多列来旋转我的表。

Employee_ID ProcessingMonth Amount      FinancialYear
3           April           41668.00    2017
3           June            41668.00    2017
3           March           41668.00    2017
3           May             41668.00    2017
4           April           10037.92    2017
4           June            10037.92    2017
4           March           10037.92    2017
4           May             10037.92    2017

我想要下面的结果

Employee_ID year jan feb mar      apr      may      june     jul aug sep oct nov dec
3           2017 0   0   41668.00 41668.00 41668.00 41668.00 0   0   0   0   0   0
4           2017 0   0   10037.92 10037.92 10037.92 10037.92 0   0   0   0   0   0

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT *
FROM (
    SELECT 
          SUM(Amount) AS sum_amount
        , Employee_ID
        , FinancialYear
        , ProcessingMonth
    FROM your_table
    GROUP BY
          Employee_ID
        , FinancialYear
        , ProcessingMonth
) t
PIVOT (SUM(sum_amount)
    FOR ProcessingMonth IN ( 
        [January], [February], [March], [April], [May], [June], [July], [August], [September], [October], [November], [December])
    ) AS pvt;

答案 1 :(得分:0)

当条件聚合更简单时,为什么希望使用pivot

SELECT Employee_ID,
       SUM(CASE WHEN ProcessingMonth = 'January' THEN Amount ELSE 0 END) as Jan,
       SUM(CASE WHEN ProcessingMonth = 'February' THEN Amount ELSE 0 END) as Feb,
       . . . 
FROM t
GROUP BY Employee_ID, FinancialYear;

不需要子查询。您将获得指定的列名称。