Reputation: 11
I have table that looks like
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
I want to see it like
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
Using SQL Server 2008
Upvotes: 0
Views: 1290
Reputation: 1269463
Use 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;
Upvotes: 2
Reputation: 571
Create a new table with the correct columns. Then use an INSERT statement with a SELECT query using UNION ALL to get the values
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 );
Upvotes: 1
Reputation: 22811
Most probably this runs faster
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;
Upvotes: 1