在SQL中将记录重复为逗号分隔列

时间:2015-08-17 18:01:23

标签: sql

VillageId     MDL        Village         PINCode
101           A1           ABC           505330
102           A1           DEF           505330
103           A1           CDF           505330
104           A2           LMN           505331
105           A2           KLM           505331
106           A4           RST           623212

我想在结果中将重复记录显示为逗号分隔列。这里有重复的记录 其中MDL和PINCODE都应匹配。

 MDL           Village           PINCode
---------------------------------------------
  A1          ABC,DEF,CDF         505330
  A2           LMN,KLM            505331
  A4            RST               623212

到目前为止,我尝试编写一个函数

CREATE FUNCTION dbo.ListComma 
( 
     @PINCode varchar(11),
    @MDL varchar(MAX)

) 
RETURNS VARCHAR(8000) 
AS 
BEGIN 
    DECLARE @r VARCHAR(8000) 
      SELECT @r = ISNULL(@r+', ', '') +  Village 
      FROM dbo.tblVillageData
      WHERE MDL= @MDL
        and PINCODE = @PINCode   
    RETURN @r 
END 

1 个答案:

答案 0 :(得分:4)

SQL Server:

使用STUFFXML Path,您可以轻松完成此操作:

SELECT DISTINCT MDL
    ,STUFF((
            SELECT ',' + t1.Village
            FROM dbo.tblVillageData T1
            WHERE T1.MDL = T2.MDL
              AND T1.PINCode = T2.PINCode
            FOR XML PATH('')
            ), 1, 1, '') AS Village
    ,PINCode
FROM dbo.tblVillageData T2;

SQL Server Demo

<强> MySQL的:

如果您使用的是MySQL数据库,那么您只需使用GROUP_CONCAT即可:

SELECT 
     MDL
    ,GROUP_CONCAT(Village) AS Village
    ,PINCode
FROM Test T2
GROUP BY MDL;

MySQL Demo

<强>更新

如果您在评论中提供了多个重复Village值,则可以使用子查询中的distinct轻松处理它们:

SELECT Distinct  MDL
    ,STUFF((
            SELECT distinct ',' + t1.Village   --add distinct here
            FROM Test T1
            WHERE T1.MDL = T2.MDL
              AND T1.PINCode = T2.PINCode
            FOR XML PATH('')
            ), 1, 1, '') AS Village
    ,PINCode
FROM Test T2;

Duplicates Village Demo