如何对两列使用pivot?

时间:2017-11-01 09:55:49

标签: sql-server sql-server-2014

我有这张桌子:

   MoveDate      Typ     Amount    Capacity
  2017-01-01      A       1000        10
  2017-01-01      B        2000       20
   2017-03-05     A        3000       5
  2017-06-08      C        1500       6

并想要这个结果:

MoveDate     A      Capacity    B      Capacity    C    Capacity
2017-01-01    1000     10       2000        20     NULL    NULL  
2017-03-05    3000     5         NULL       NULL   NULL    NULL
2017-06-08    NULL     NULL      NULL      NULL    1500      6

如何使用pivot或其他方法实现它?

2 个答案:

答案 0 :(得分:1)

您还可以使用动态SQL查询来实现此目的。

<强>查询

declare @sql as varchar(max);
select @sql = stuff((
        select ',sum(case [Typ] when ' + char(39) + [Typ] + char(39) 
              + ' then [Amount] end) as [' + [Typ] + '],
              sum(case [Typ] when ' + char(39) + [Typ] + char(39) 
              + ' then [Capacity] end) as [Capacity] '
        from  [your_table_name]
        for xml path('')
    )
    , 1, 1, ''
);

select @sql = 'select [MoveDate], ' + @sql 
              + ' from [your_table_name] group by [MoveDate];';

exec(@sql);

答案 1 :(得分:0)

尝试这样的事情。

SELECT
  MoveDate,
  SUM(CASE WHEN Typ = 'A' THEN Amount END) AS A,
  SUM(CASE WHEN Typ = 'A' THEN Capacity END) AS Capacity,
  SUM(CASE WHEN Typ = 'B' THEN Amount END) AS B,
  SUM(CASE WHEN Typ = 'B' THEN Capacity END) AS Capacity,
  SUM(CASE WHEN Typ = 'C' THEN Amount END) AS C,
  SUM(CASE WHEN Typ = 'C' THEN Capacity END) AS Capacity
FROM myTable
GROUP BY MoveDate