在SQL Server中将单行转换为多行

时间:2016-04-27 11:20:25

标签: sql sql-server sql-server-2008

我的表格看起来像

lastName1   FirstName1  Address1    City1   State1  Zip1    lastName2   FirstName2  Address2    City2   State2  Zip2    lastName3   FirstName3  Address3    City3   State3  Zip3
Williams    Greg    123 W Main  NEWCITY MI  48056   Butler  Jos 456 E 7th AVE   OLDCITY MI  48134   BRESNAN TIM 789 N Rd    SAMECITY    MI  45678
George  Adam    321 W MAIN Rd   NEWCITY MI  48056   Thompson    Mark    645 E 7th AVE   OLDCITY MI  48134   Jordan  Hal 987 N Rd    SAMECITY    MI  45678

我希望看到它像

lastName    FirstName   Address City    State   Zip
Williams    Greg    123 W Main  NEWCITY MI  48056
Butler  Jos 456 E 7th AVE   OLDCITY MI  48134
BRESNAN TIM 789 N Rd    SAMECITY    MI  45678
George  Adam    321 W MAIN Rd   NEWCITY MI  48056
Thompson    Mark    645 E 7th AVE   OLDCITY MI  48134
Jordan  Hal 987 N Rd    SAMECITY    MI  45678

使用SQL Server 2008

3 个答案:

答案 0 :(得分:2)

使用union all

select lastname1 as lastname, firstname1 as firstname, city1 as city, state1 as state, zip1 as zip
from t
where lastname1 is not null
union all
select lastname2 as lastname, firstname2 as firstname, city2 as city, state2 as state, zip2 as zip
where lastname2 is not null
from t
union all
select lastname3 as lastname, firstname3 as firstname, city3 as city, state3 as state, zip3 as zip
from t
where lastname3 is not null;

答案 1 :(得分:1)

使用正确的列创建一个新表。 然后使用带有SELECT查询的INSERT语句,使用UNION ALL获取值

INSERT INTO NewTableName (lastname, firstname, city, state, zip)

VALUES 

(SELECT lastname1 AS lastname, firstname1 AS firstname, city1 AS city, state1 AS state, zip1 AS zip
FROM OldTableName 
UNION ALL

SELECT lastname2 AS lastname, firstname2 AS firstname, city2 AS city, state2 AS state, zip2 AS zip
FROM OldTableName 
UNION ALL

SELECT lastname3 AS lastname, firstname3 AS firstname, city3 AS city, state3 AS state, zip3 AS zip
FROM OldTableName );

答案 2 :(得分:1)

很可能这会跑得更快

select r.lastname, r.firstname, r.city, r.state, r.zip
from t 
cross apply (
select lastname1 as lastname, firstname1 as firstname, city1 as city, state1 as state, zip1 as zip
where lastname1 is not null
union all
select lastname2 as lastname, firstname2 as firstname, city2 as city, state2 as state, zip2 as zip
where lastname2 is not null
union all
select lastname3 as lastname, firstname3 as firstname, city3 as city, state3 as state, zip3 as zip
where lastname3 is not null) r;