将行分组到多个列

时间:2015-12-07 11:45:30

标签: sql sql-server

我正在尝试转换它:

Name, YearMonth, Quantity, Rate
-------------------------------
Aaron, 201001, 10, 5
Aaron, 201002, 13, 6
Adriana, 201001, 15, 7
Adriana, 201002, 9, 8

到此:

Name, 201001-Quantity, 201001-Rate, 201002-Quantity, 201002-Rate   
-----------------------------------------------------------------
Aaron, 10, 5, 13, 6
Adriana, 15, 7, 9, 8

我试过使用PIVOT,但看起来你只能在1列

上转动

1 个答案:

答案 0 :(得分:0)

您可以使用条件聚合:

select name,
       sum(case when yearmonth = 201001 then quantity end) as quantity_201001,
       sum(case when yearmonth = 201001 then rate end) as rate_201001,
       sum(case when yearmonth = 201002 then quantity end) as quantity_201002,
       sum(case when yearmonth = 201002 then rate end) as rate_201002
from t
group by name;

这是ANSI标准SQL,应该适用于任何数据库。