sql行为2行和列

时间:2017-04-21 13:22:43

标签: sql sql-server

我现在有一个包含4列的表格,project_id,month,forecast,actual。

每个项目有12行(12个月)。

我想将此转换为每个记录有2行(实际和预测)的位置以及每个月的12列?

有没有办法在sql server中轻松实现这一点?或者我必须为实际和预测做一个工会?

示例数据:(抱歉,我不知道如何将其放在表格格式中)

project_id | month | forecast | actual
111        | jan   | 35       | 30
111        | feb   | 36       | 31
111        | mar   | 45       | 3
....

欲望结果

project_id | type     | Jan | Feb | Mar ....
111        | actual   | 30  | 31  | 3
111        | forecast | 35  | 36  | 45

1 个答案:

答案 0 :(得分:2)

您可以使用pivot和union all,如下所示:

select * from  (
    select project_id, month, forecast from #yourproject ) s
    pivot (max(forecast) for month in ([jan],[feb],[mar],[apr],[may],[jun],[jul],[aug],[sep],[oct],[nov],[dec])) p
Union all
select * from  (
    select project_id, month, actual from #yourproject ) s
    pivot (max(actual) for month in ([jan],[feb],[mar],[apr],[may],[jun],[jul],[aug],[sep],[oct],[nov],[dec])) p

您的输入表:

 create table #yourproject (project_id int, month varchar(3), forecast int, actual int)

 insert into #yourproject (project_id, month, forecast, actual) values
 (111       ,'jan',  35   , 30 )
,(111       ,'feb',  36   , 31 )
,(111       ,'mar',  45   , 3  )
--your records continues