Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
procyon4476
Starting Member
4 Posts |
Posted - 2009-06-14 : 17:28:24
|
Hello, new to sql and had a quick question about how to write a query, if its even possible.My data is a little more complicated than this but this should give you a good idea what I want to do. Say I have one table that has names of people:NAMEBRIANBOBBY Second table has the same names and cities they have lived in, duplicating names are on multiple lines:NAME CITYBRIAN PHOENIXBRIAN SEATTLEBOBBY MIAMIBOBBY ATLANTABOBBY DALLAS I want to write a query that shows every name on a single line and showing each city they have lived in left to right, each city in multiple columns. For the sake of argument, say I know the maximum number of cities that any person has lived in. So the query results would look something like this:NAME CITY1 CITY2 CITY3BRIAN PHOENIX SEATTLEBOBBY MIAMI ATLANTA DALLAS Ok, so I guess for this example the first table is pointless, but in my actual data it matters.Anyway to write something like this? Multiple queries are ok if necessary. Thanks for any help! |
|
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2009-06-14 : 21:13:02
|
[code]DECLARE @people TABLE( [name] varchar(10))DECLARE @city TABLE( [name] varchar(10), [city] varchar(10))INSERT INTO @peopleSELECT 'BRIAN' UNION ALLSELECT 'BOBBY'INSERT INTO @citySELECT 'BRIAN', 'PHOENIX' UNION ALLSELECT 'BRIAN', 'SEATTLE' UNION ALLSELECT 'BOBBY', 'MIAMI' UNION ALLSELECT 'BOBBY', 'ALANTA' UNION ALLSELECT 'BOBBY', 'DALLAS'SELECT [NAME] = [name], [CITY1] = [1], [CITY2] = [2], [CITY3] = [3], [CITY4] = [4], [CITY5] = [5]FROM( SELECT p.[name], c.[city], seq_no = row_number() OVER (PARTITION BY p.[name] ORDER BY c.[city]) FROM @people p INNER JOIN @city c ON p.[name] = c.[name]) dpivot( MAX([city]) FOR seq_no IN ([1], [2], [3], [4], [5])) p/*NAME CITY1 CITY2 CITY3 CITY4 CITY5 ---------- ---------- ---------- ---------- ---------- ---------- BOBBY ALANTA DALLAS MIAMI NULL NULLBRIAN PHOENIX SEATTLE NULL NULL NULL(2 row(s) affected)*/[/code] KH[spoiler]Time is always against us[/spoiler] |
 |
|
|
procyon4476
Starting Member
4 Posts |
Posted - 2009-06-14 : 23:19:50
|
| Thanks!! |
 |
|
|
|
|
|
|
|