如何在SQL Server中将多行组合成一行和多列?

时间:2017-08-25 08:00:33

标签: 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 as sale
  • 2作为购买
  • 3作为回报

现在我想将结果集显示如下

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

我尝试但无法生成此结果集。有人可以帮忙吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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];