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
 SQL Server 2000 Forums
 Transact-SQL (2000)
 get all records on one row.

Author  Topic 

jryannel
Starting Member

13 Posts

Posted - 2004-01-28 : 13:50:45
I'm sure this has been asked a lot, but I have 2 tables with data but want to join the information into one record. Basically i have a customer and invoice table. I want to join the customer on his invoice or invoices and get all the invoices on the same row as the customer. I'm not great with joins, but my code below returns a row per invoice.

I want this

company invoice invoice invoice
------- ------- ------- -------
company1 1 2 3
company2 4 null null
company3 5 6 null


instead i get this

company invoice
------- -------
company1 1
company1 2
company1 3
company2 4
company3 5


select SDC.company,sdo.id
from sd_customers SDC
left outer join sd_orders SDO
on sdc.id = sdo.customerid

group by sdc.company,sdo.id

thanks, jeff

setbasedisthetruepath
Used SQL Salesman

992 Posts

Posted - 2004-01-28 : 14:46:48
First, converting the rowset in that manner is typically a presentation-layer issue, so I would recommend you not do this on the database side. Second, it's problematic because you don't know how many columns you need for the rowset, as it depends on the max # of invoices for any given company. It can be done though, search this site for examples if you really really want this.

Jonathan
Gaming will never be the same
Go to Top of Page

X002548
Not Just a Number

15586 Posts

Posted - 2004-01-28 : 15:18:14
Yeah, what he said....but I'm bored...


USE Northwind
GO

CREATE TABLE myTable99(Col1 varchar(10), Col2 char(1))
GO
INSERT INTO myTable99(Col1,Col2)
SELECT 'company1', '1' UNION ALL
SELECT 'company1', '2' UNION ALL
SELECT 'company1', '3' UNION ALL
SELECT 'company2', '4' UNION ALL
SELECT 'company3', '5'
GO

DECLARE @x TABLE (y varchar(10), z varchar(8000))

DECLARE @y varchar(10), @z varchar(8000)
DECLARE myCursor99 CURSOR
FOR
SELECT DISTINCT Col1 FROM myTable99 ORDER BY Col1

OPEN myCursor99

FETCH NEXT FROM myCursor99 INTO @y

WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @z = COALESCE(@z + ', ', '') + Col2
FROM myTable99
WHERE Col1 = @y
INSERT INTO @x(y,z) SELECT @y, @z
FETCH NEXT FROM myCursor99 INTO @y
SELECT @z = NULL
END
SELECT * FROM @x

CLOSE myCursor99
DEALLOCATE myCursor99
GO

DROP TABLE myTable99
GO





Brett

8-)
Go to Top of Page

drymchaser
Aged Yak Warrior

552 Posts

Posted - 2004-01-28 : 17:35:08
Or search Dynamic Cross-Tab on this site. However, there are limitations to this solution and a large count of invoices per company could cause problems.

I highly recommend doing this at the presentation layer.
Go to Top of Page
   

- Advertisement -