1

I have the following recordset:

ID      AssetName
882     Training Room VCR
882     Training Room DVD
882     Training Room TV
858     Training Room VCR
858     Training Room Computer
858     Training Room TV

I want to group each ID and get a resultset as such:

ID      Assets
882     Training Room VCR<br/>Training Room DVD<br/>Training Room TV
858     Training Room VCR<br/>Training Room Computer<br/>Training Room TV   

Is there a way to build a SQL 2005 statement that will do this?


duplicate question

How to return multiple values in one column (T-SQL)?

Community
  • 1
  • 1
Steve Wright
  • 2,481
  • 3
  • 26
  • 35

2 Answers2

1

I recommend keeping the logic for adding the <br /> elements in your server-side code, not the SQL query. Keep your SQL focused on returning the result set and use loops in your code to figure out how to present it like that.

A first attempt might involve a query-based loop with another query-based loop inside it, but that will result in a bombardment of queries on your database. It's better to use a single large query result and have logic branches for conditional output. Modify your query to facilitate the desired output, not create it. For instance, you might order the data so you know you'll be getting all the assets of one ID before moving on to the next.

SurroundedByFish
  • 2,900
  • 2
  • 22
  • 17
1

This will get what you need.

SELECT DISTINCT
    [ID]
    ,CONVERT(VARCHAR(MAX),
    (   SELECT [AssetName] [div]
        FROM [dbo].[tableName] t1 
        WHERE t1.[ID] = t.[ID] FOR XML PATH('')
    )) [asset]
FROM [dbo].[tableName] t
Slim
  • 5,635
  • 7
  • 31
  • 30
  • This gives the records in this format:
    Smart Board
    In conference room 434
    VCR/DVD player in conference room 434
    – Steve Wright Jun 30 '09 at 18:03
  • Then try this SELECT DISTINCT [ID] ,REPLACE(CONVERT(VARCHAR(MAX), ( SELECT [AssetName] + 'XXX' FROM [dbo].[tableName] t1 WHERE t1.[ID] = t.[ID] FOR XML PATH('') )), 'XXX', '
    ') [asset] FROM [dbo].[tableName] t
    – Slim Jun 30 '09 at 18:25