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.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Script all records to one line for 1 to many

Author  Topic 

markfigel
Starting Member

8 Posts

Posted - 2008-10-23 : 10:27:17
Hi,

In a one to many scenario, I need to have all of the records in the many table appear in one line/record. I cannot use a static reference to pull the Addr.Code value because the codes vary.

Here is an example of the tables and the result I need to achieve. Any ideas?

dbo.Vendor Master
ID Name
1000 FedEx


dbo.Vendor Address
ID Code State
1000 Primary NY
1000 Remit FL


Result Required
ID Name Code State Code State
1000 FedEx Primary NY Remit FL

Thanks

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-10-23 : 10:30:15
Will you be certain about number of code,state values existing for an ID?or atleast what can be max number of values?
Go to Top of Page

markfigel
Starting Member

8 Posts

Posted - 2008-10-23 : 10:51:12
The max vendor codes/states per vendor is 7. However there are 100+ distinct address codes.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-10-23 : 11:01:26
quote:
Originally posted by markfigel

The max vendor codes/states per vendor is 7. However there are 100+ distinct address codes.


Are you using sql 2005?
Go to Top of Page

markfigel
Starting Member

8 Posts

Posted - 2008-10-23 : 11:19:19
Yes
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-10-23 : 11:41:48
[code]SELECT ID,
MAX(CASE WHEN Seq=1 THEN Code ELSE NULL END) AS Code1,
MAX(CASE WHEN Seq=1 THEN State ELSE NULL END) AS State1,
MAX(CASE WHEN Seq=2 THEN Code ELSE NULL END) AS Code2,
MAX(CASE WHEN Seq=2 THEN State ELSE NULL END) AS State2,
...
MAX(CASE WHEN Seq=7 THEN Code ELSE NULL END) AS Code7,
MAX(CASE WHEN Seq=7 THEN State ELSE NULL END) AS State7
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY vm.ID ORDER BY va.AddressID) AS Seq,va.ID,va.Code,va.State,vm.Name
FROM dbo.[Vendor Master] vm
INNER JOIN dbo.[Vendor Address] va
ON va.ID=vm.ID
)t
GROUP BY ID[/code]
Go to Top of Page

markfigel
Starting Member

8 Posts

Posted - 2008-10-23 : 11:47:13
Thanks, I'll try and advise
Go to Top of Page
   

- Advertisement -