sql将5列写入2列

时间:2012-08-03 15:33:48

标签: sql database tsql

我有一个包含5列的sql视图。我希望将数据写入表中,但只有2列,

视图

id 
car1
car2
car3
car4

id
cars

INSERT INTO table 
SELECT * from view

3 个答案:

答案 0 :(得分:2)

insert cars (id, car)
select id, cars
from view
unpivot
(cars for car in (car1, car2,car3, car4)) as u

答案 1 :(得分:2)

蛮力和无知(但可靠):

INSERT INTO table
   SELECT id, car1 FROM view WHERE car1 IS NOT NULL
   UNION
   SELECT id, car2 FROM view WHERE car2 IS NOT NULL
   UNION
   SELECT id, car3 FROM view WHERE car3 IS NOT NULL
   UNION
   SELECT id, car4 FROM view WHERE car4 IS NOT NULL

UNION具有消除任何重复的优点。

答案 2 :(得分:1)

你试过这个吗?

INSERT INTO table SELECT ID, Car1 + ',' + Car2 + ',' + Car3 + ',' + Car4 as Cars from view