SQL Server:连接值

时间:2013-07-23 08:29:11

标签: sql sql-server tsql

以下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字段与外部表链接

2 个答案:

答案 0 :(得分: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 |

请参阅this SQLFiddle

答案 1 :(得分: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 DEMO - 简化CT CTE