2017-08-25 53 views
1

我要通過我做了臨時表不同的表,這裏是結果集臨時表的:如何在SQL Server中將多行組合成一行和多列?

 car_id | car_type | status | count 
    --------+----------+---------+------ 
    100421 | 1  | 1  | 9 
    100421 | 1  | 2  | 8 
    100421 | 1  | 3  | 3 
    100421 | 2  | 1  | 6 
    100421 | 2  | 2  | 8 
    100421 | 2  | 3  | 3 
    100422 | 1  | 1  | 5 
    100422 | 1  | 2  | 8 
    100422 | 1  | 3  | 7 

下面是狀態欄的含義:

  • 1作爲銷售
  • 2作爲購買
  • 3作爲回報

現在我想將此resul t設置如下

car_id | car_type | sale | purchase | return 
    --------+----------+------+----------+---------- 
    100421 | 1  | 9 | 8  | 3 
    100421 | 2  | 6 | 8  | 3 
    100422 | 1  | 5 | 8  | 7 

我試過但無法生成這個結果集。誰能幫忙?

回答

3

試試這個

select car_id ,car_type, [1] as Sale,[2] as Purchase,[3] as [return] 
from (select car_id , car_type , [status] ,[count] from tempTable)d 
pivot(sum([count]) for [status] in([1],[2],[3])) as pvt 

也可以刪除子查詢,如果你沒有任何條件 像

select car_id ,car_type, [1] as Sale,[2] as Purchase,[3] as [return] 
from tempTable d 
pivot(sum([count]) for [status] in([1],[2],[3])) as pvt 
+0

不工作的car_type – Umer

+0

對不起,我心中已經編輯查詢,目前正在測試其工作後, –

3

你也可以使用一個CASE表達。

查詢

select [car_id], [car_type], 
max(case [status] when 1 then [count] end) as [sale], 
max(case [status] when 2 then [count] end) as [purchase], 
max(case [status] when 3 then [count] end) as [return] 
from [your_table_name] 
group by [car_id], [car_type] 
order by [car_id];