Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
Solved

# How to collapse rows returned from SQL SELECT into one?

Posted on 2004-04-06
Medium Priority
463 Views
Hello,

the following query joins two tables and produces the following results:

SELECT DT1.Name, DT1.SectorID, DT1.ExposureBiasID, DT2.AssetClassID
FROM DT_Strategy DT1, DT_StrategyAssetClass DT2
WHERE DT1.ID = DT2.StrategyID AND DT1.ID = 1

------------------------------------------------------------------
Relative Value Equity Long      4      1      1
Relative Value Equity Long      4      1      2
Relative Value Equity Long      4      1      3
------------------------------------------------------------------

All the resulting rows are equal except for the value in the last column. I would like to collapse them into one row as follows:

----------------------------------------------------------------------
Relative Value Equity Long      4      1      1,2,3
----------------------------------------------------------------------

Is this possible in SQL? Or do I need to do it programatically?

Thanks,
Stefano
0
Question by:sdamiano
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points

LVL 70

Accepted Solution

Scott Pletcher earned 1000 total points
ID: 10770277
On SQL 2000, you can use a user-defined function.  For example:

CREATE FUNCTION dbo.getAssetClassIDs (
@ID INT
)
RETURNS VARCHAR(1000)
AS
BEGIN
DECLARE @AssetClassIDs VARCHAR(1000)
SET @AssetClassIDs = ''
SELECT @AssetClassIDs = @AssetClassIDs + CAST(AssetClassID AS VARCHAR(10)) + ','
FROM DT_StrategyAssetClass
WHERE StrategyID = @ID
RETURN LEFT(@AssetClassIDs, LEN(@AssetClassIDs) - 1)
END --FUNCTION
GO

Then, to use the function:

SELECT DT1.Name, DT1.SectorID, DT1.ExposureBiasID, dbo.getAssetClassIDs(DT1.ID)
FROM DT_Strategy DT1
WHERE DT1.ID = 1
0

Author Comment

ID: 10770600
Scott,

it works perfectly!

Thanks,
Stefano
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includâ€¦
I have a large data set and a SSIS package. How can I load this file in multi threading?
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
###### Suggested Courses
Course of the Month6 days, 4 hours left to enroll