I suppose this is a common problem but I was stuck on this for a while, until I found a helpful article (which I've now lost!) proposing a solution if you're using SQL Server 2000.

Needing to get a single row of data from tables with a one-to-many relationship.

tbl_users     tbl_results    
USER_ID USERNAME   ID USER_ID RECORD
1 Phill   1 1 Good
      2 1 Bad
      3 1 Average

Using an outer join you would get 3 records

qry_results  
USER_ID RECORD
1 Good
1 Bad
1 Average

However I needed 1 row not 3, like this:

qry_results  
USER_ID RECORD
1 Good,Bad,Average

Solution.

In order to get the desired result I created a function. The function queries the table and concatenates the rows together using the Coalesce() function. Here's a version of the query I used:

CREATE FUNCTION dbo.RowsToString
( @USER_ID int )
RETURNS Varchar(8000)
AS
BEGIN
DECLARE @Result Varchar(8000)
SELECT @Result = Coalesce(@Result + ', ', '') + TR.Record FROM tbl_results TR
WHERE TR.USER_ID = @USER_ID
RETURN ( @Result )
END

Then call the function within a query, or cfquery, as follows:


SELECT USER_ID, dbo.RowsToString(USER_ID) AS RECORDS
FROM tbl_users


Result:

qry_results  
USER_ID RECORD
1 Good,Bad,Average

 


No Comments on “Grouping multiple records into a single row of a query”

You can track this conversation through its atom feed.

No one has commented on this entry yet.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>