SQL Server:跨多个列进行透视

时间:2012-01-20 10:04:52

标签: sql-server pivot

我有一个严重的问题。假设我的数据以这种格式排列:

Name      Businees_unit  Forecast  Upside
Jack.N    India          100       50
Jack.N    China          250       20

我必须为Forecast转动UpsideBusiness_Unit,以便表格看起来像这样

Name    Forecast_India    Upside_India      Forecast_China    Upside_China
Jack    100               50                250               20

这可以在一个查询中完成吗?

这是我的第一次参赛,所以非常欢迎任何帮助。

由于

2 个答案:

答案 0 :(得分:1)

通用解决方案:

select name,
       sum(case when Businees_unit = 'India' then Forecast else 0 end) Forecast_India,
       sum(case when Businees_unit = 'India' then Upside else 0 end) Upside_India,
       sum(case when Businees_unit = 'China' then Forecast else 0 end) Forecast_China,
       sum(case when Businees_unit = 'China' then Upside else 0 end) Upside_China
from My_table
group by name

答案 1 :(得分:0)

我会使用自我加入:

SELECT DISTINCT SomeTable.Name, China.Forecast as Forecast_China, China.Upside as Upside_China
, India.Forecast as Forecast_India, India.Upside as Upside_India
FROM SomeTable
inner join SomeTable India on India.Name = SomeTable.Name AND India.Business_unit = 'India'
inner join SomeTable China on China.Name = SomeTable.Name AND China.Business_unit = 'China'