2012-01-20 31 views
1

我有一個嚴重的問題。說我的數據被安排在此格式:SQL Server:跨多個colums的支點

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

我必須轉動ForecastUpsideBusiness_Unit使表看起來就像這樣

Name Forecast_India Upside_India  Forecast_China Upside_China 
Jack 100    50    250    20 

這可以在一個查詢做什麼?

它是我的第一個入口,所以任何幫助都非常受歡迎。

感謝

+1

哪個(RDBMS的SQLServer,Oracle,MySQL等等),是這樣嗎? –

回答

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 
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' 
+0

因爲[Jack.N]在表格中出現兩次,所以你正在返回兩個相同的行 – Robb

+0

相當正確,我忘了明顯的,現在應該工作:) – RobJohnson