2017-08-25 51 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];