2

The following SQL Server query need help

select 
    JI.id, RBIEnvironment
from
   (select 
       issue,
       case when cfname='RBI-Environment' 
              then customvalue 
             else null 
       end as 'RBIEnvironment' 
    from X) as CT
where 
    CT.issue = JI.id
group by 
    JI.id, RBIEnvironment

The issue is the CT table returns the data in following format

1   NULL
1   STG
1   PROD
2   SIT
2   DIT
3   SIT

Hence the outer query returns

1   NULL
1   STG
1   PROD
2   SIT
2   DIT
3   SIT

I need in following format

1   STG,PROD
2   SIT,DIT
3   SIT

Please use the same inner dynamic table as such as it contains some more columns which needs to be displaye din the resultselt .This inner table is linked with the outer table using the issue field and ID field respectively

Alfaromeo
  • 379
  • 2
  • 6
  • 14

2 Answers2

2

Try STUFF() function for that:

SELECT distinct ID, RBIEnvironment = 
    STUFF((SELECT ' , ' + RBIEnvironment
           FROM MyTable b 
           WHERE b.ID = a.ID
          FOR XML PATH('')), 1, 2, '')
FROM MyTable a
GROUP BY ID;

Output:

| ID | RBIENVIRONMENT |
-----------------------
|  1 |     STG , PROD |
|  2 |      SIT , DIT |
|  3 |            SIT |

See this SQLFiddle

Himanshu
  • 31,810
  • 31
  • 111
  • 133
1

You can use STUFF..FOR XML construct for concatenating column values.

WITH CT AS 
(
    select issue,
        case when cfname='RBI-Environment' 
                then customvalue 
             else null 
             end as 'RBIEnvironment' 
    from X
)
SELECT issue, 
STUFF((SELECT ', ' + b.RBIEnvironment 
       FROM CT b 
        WHERE a.issue = b.issue 
         FOR XML PATH('')),1,1,'')
FROM CT a
GROUP BY a.issue

SQLFiddle DEMO - simplified for CT CTE

Nenad Zivkovic
  • 18,221
  • 6
  • 42
  • 55