2

以下 SQL Server 查询需要帮助

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

问题是CT表格以以下格式返回数据

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

因此外部查询返回

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

我需要以下格式

1   STG,PROD
2   SIT,DIT
3   SIT

请使用相同的内部动态表,因为它包含更多需要在结果中显示的列。该内部表分别使用问题字段和 ID 字段与外部表链接

4

2 回答 2

2

尝试STUFF()功能:

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;

输出:

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

看到这个 SQLFiddle

于 2013-07-23T08:33:41.983 回答
1

您可以使用STUFF..FOR XML构造来连接列值。

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 DEMOCT - 为CTE简化

于 2013-07-23T08:40:41.077 回答