Bhupendra Shukla
Bhupendra Shukla

Reputation: 3904

SQL Query to produces Comma Seperated Column from redundent Rows?

I have two table, which are joined together and stored in a temp table.

The Temp table consist the data in following form:

|ID|Name |Code|  
|1 | 100 |AAAA|
|1 | 100 |AAAB|
|1 | 100 |AAAA|
|2 | 200 |AAAZ|
more...

Now I want the outcome in the following form,

╔════╦═════════════════════╗
║ ID ║ Name ║   Code       ║
╠════╬═════════════════════╣
║  1 ║ 100  ║   AAAA, AAAB ║
║  2 ║ 200  ║   AAAZ       ║
╚════╩═════════════════════╝

So I have written the Following Query, which produces the similar output, So my question is that, Is there any other way to achieve this.

SELECT Distinct BSE_ID
    ,BSE_Name
    ,STUFF((
            SELECT ', ' + CAST(EBS_ExternalCode AS VARCHAR(100)) [text()]
            FROM #tmpBkgSvc
            WHERE BSE_ID = T.BSE_ID
            FOR XML PATH('')
                ,TYPE
            ).value('.', 'NVARCHAR(MAX)'), 1, 2, ' ') EBS_ExternalCode
FROM #tmpBkgSvc T

Upvotes: 1

Views: 105

Answers (3)

Saharsh Shah
Saharsh Shah

Reputation: 29051

Use Cross Apply instead of Sub Query

SELECT T.BSE_ID, T.NAME, MAX(STUFF(A.BSE_ID_LIST, 1, 1, '')) AS BSE_ID_LIST
FROM #tmpBkgSvc T
CROSS APPLY (
    SELECT ', ' + CAST(EBS_ExternalCode AS VARCHAR(100))
    FROM #tmpBkgSvc T1
    WHERE T1.BSE_ID = T.BSE_ID
    GROUP BY T1.EBS_ExternalCode 
    ORDER BY T1.EBS_ExternalCode 
    FOR XML PATH('')
) AS A (BSE_ID_LIST)
GROUP BY T.BSE_ID, T.NAME

Upvotes: 0

Azar
Azar

Reputation: 1867

Try this

Create function Fun
(
    @id int, @name varchar(100)
)
returns varchar(max)
as
begin 

       Declare @code varchar(max)
       Select @code = isnull(@code+',','')+s.code
       from (Select distinct code 
              from table 
               where name = @name and id = @id) s
       Return @code
end

Select id,name,[dbo].Fun(id,Name) 'Code' from table group by id,name

Upvotes: 1

try like this, Use group By In the Code column

SELECT Distinct ID, Name
    ,STUFF((
            SELECT ', ' + CAST(Code AS VARCHAR(100)) [text()]
            FROM DataTable
            WHERE ID = T.ID Group By Code //group by does the magic here
            FOR XML PATH('')
                ,TYPE
            ).value('.', 'NVARCHAR(MAX)'), 1, 2, ' ') Code 
FROM DataTable T

Upvotes: 0

Related Questions