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 |
|
kyledunn
Starting Member
7 Posts |
Posted - 2003-03-28 : 08:44:31
|
| I have two tables that have been joined into a single table. The first table contains primary key Customer Number and Customer Name. The second table contains a foreign key Customer Number and Location Number. There can be multiple locations for each customer. When I join these two tables withSelect Table1.CustomerNumber, Table1.CustomerName, Table2.LocationNumber from Table1, Table2 where Table1.CustomerNumber = Table2. CustomerNumberI get a new table with three columns, Customer Number Customer Name and Location with a repeating Customer Number and Name for each location.Is it possible with a query to turn this into a table with a single row for each customer number and name with a column for each location? The total number of columns would be determined by the customer with the most locations and those with fewer locations would have a null value for the unfilled columns.Here is the example results:Start with:Cus# Name Location1 John 11 John 21 John 32 Mike 42 Mike 53 Bob 6With miracle query:Cus# Name Loc1 Loc2 Loc31 John 1 2 32 Mike 4 5 null3 Bob 6 null nullCan you show me what the query would look like to accomplish this? Thanks for any help!Kyle |
|
|
jsmith8858
Dr. Cross Join
7423 Posts |
Posted - 2003-03-28 : 09:16:55
|
| Kyle --today is your lucky day.The only caveat to what I am posting below is you know the maximum # of columns that any customer can have.Take a look:select cus#, max(case when LocNumber =1 then location else null end) as Loc1, max(case when LocNumber =2 then location else null end) as Loc2, max(case when LocNumber =3 then location else null end) as Loc3, max(case when LocNumber =4 then location else null end) as Loc4 .. etc ...from(select cus#, location, (select count(*) from tbl where tbl.cus# = a.cus# and tbl.location <= a.location) as LocNumberfromtbl a)bgroup by cus#That should return exactly what you are looking for ... but make sure you have enough columns to handle all cases.- Jeff |
 |
|
|
SamC
White Water Yakist
3467 Posts |
Posted - 2003-03-28 : 09:49:13
|
I registered for email notification to see if anyone had a solution.I'd imagined adding a column with a counter. Jeff's solution avoided altering the table.Nice work Sam |
 |
|
|
|
|
|