SQL Query从冗余行生成逗号分隔列?

时间:2014-06-30 09:12:33

标签: sql select group-by sql-server-2012 sql-server-group-concat

我有两个表,它们连接在一起并存储在临时表中。

Temp表包含以下形式的数据:

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

现在我希望以下列形式获得结果,

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

所以我编写了以下查询,它产生了类似的输出,所以我的问题是,还有其他方法可以实现这一点。

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

3 个答案:

答案 0 :(得分:1)

试试这个

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

答案 1 :(得分:0)

尝试这样,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

答案 2 :(得分:0)

使用交叉应用代替子查询

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