如何多次旋转一列?

时间:2015-01-29 03:47:39

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

表是

  ID  YEAR Name   Value

  1    2014  A     10
  2    2014   B    20
  1    2013   A     30

想要一张如下表:

 ID  2014   2013   A  B
 1    10    20    40  0

 2    20     0    0    20

基本上想要年份和名称的Pivot Value列。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

我会用条件聚合来做到这一点:

select id,
       sum(case when year = 2014 then value else 0 end) as [2014],
       sum(case when year = 2013 then value else 0 end) as [2013],
       sum(case when name = 'A' then value else 0 end) as [A],
       sum(case when name = 'B' then value else 0 end) as [B]
from table t
group by id;

答案 1 :(得分:0)

以下是使用pivot

的方法
SELECT id,
       Isnull([2014], 0) [2014],
       Isnull([2013], 0) [2013],
       Isnull([A], 0)    [A],
       Isnull([B], 0)    [B]
FROM   (SELECT *,
               Sum(value)OVER(partition BY Name) tot
        FROM   Yourtable) a
       PIVOT (Max(Value)
             FOR year IN ([2014],
                          [2013]))pv    
       PIVOT (Max(tot) 
             FOR name IN ([A],[B]))pv1

<强> SQLFIDDLE DEMO