如何将一列拆分为两列?

时间:2014-03-04 12:45:46

标签: sql sql-server

我在Microsoft SQL Server Management Studio中工作。

我有一个名为Car的列,女巫有两个不同的行值(沃尔沃和宝马)。如何将此列拆分为两个列(例如:Car1和Car2)。然后将“Volvo”的所有行值存储在“Car1”列中,然后将“BMW”值存储在“Car2”列中。

看起来像这样:

+-------+
|  Car  |
+-------+
| Volvo |
| Volvo |
| Volvo |
| BMW   |
| BMW   |
| Volvo |
| BMW   |
+-------+

但我希望它看起来像这样:

+-------+------+
| Car1  | Car2 |
+-------+------+
| Volvo | BMW  |
| Volvo | BMW  |
| Volvo | BMW  |
| Volvo |      |
+-------+------+

我已经尝试过SUBSTRING,CHARINDEX等一些事情......但我现在完全陷入困境。

2 个答案:

答案 0 :(得分:1)

这就是你要求的。这真的是你想要的吗?该解决方案还适用于2个以上的汽车标签。

;with x as
(
select distinct car, dense_rank() over (order by car desc) rn from car
)
select @carlist = coalesce(@carlist + ',[' + car+']', +'['+ car+']'),
       @carlist2 = coalesce(@carlist2 +','+ car + ' Car' + cast(rn as varchar(4)), car + ' Car1')
  from x
  order by rn

declare @sql varchar(max)=
';with x as
(
 SELECT car, row_number() over (partition by car order by car) rn
 FROM car
 )
SELECT '+@carlist2+'
FROM  
x 
PIVOT (max(car) FOR [car] IN ('+@carlist+')) AS pvt'

exec(@sql)

结果:

Car1  Car2
Volvo BMW
Volvo BMW
Volvo BMW
Volvo NULL

答案 1 :(得分:-2)

你可以试试这个!

;with cte as
(
select case when car='volvo' then 'volvo' else 'BMW' end as bekar from t 
)

select case when bekar='volvo' then 'volvo' else '' end as Car1,
        case when bekar='BMW' then 'BMW' else '' end as Car2
from cte

DEMO