尝试在使用coalesce后删除重复的数据行

时间:2014-06-18 17:23:20

标签: mysql sql sql-server

我有一个表,其中包含我的用户拥有的每种访问类型的记录:

cm812    BRTYF78
cm812    BRgh5VD
cm812    GHYF7GJ

我想查询表并获取:

cm812    BRTYF78,BRgh5VD,GHYF7GJ

这就是我写的:

  SELECT id
      ,COALESCE(access+',' ,'') + (access) as access 
  FROM [accesslist]
    group by id, access

我得到的是:

cm812      BRTYF78,BRgh5VD,GHYF7GJ

cm812      BRTYF78,BRgh5VD,GHYF7GJ

cm812      BRTYF78,BRgh5VD,GHYF7GJ

如何获得一个???:

的条目
cm812      BRTYF78,BRgh5VD,GHYF7GJ

2 个答案:

答案 0 :(得分:3)

SQL Server Fiddle

SELECT A.id, 
SUBSTRING((
  SELECT ', ' + B.access 
  FROM accesslist B 
  WHERE B.id = A.id
  ORDER BY access
  For XML Path('')),2,8000) AS AccessList
FROM accesslist A  
GROUP BY A.id

MySQL Fiddle

SELECT A.id, 
  GROUP_CONCAT(access ORDER BY access SEPARATOR ', ') AS AccessList
FROM accesslist A  
GROUP BY A.id

答案 1 :(得分:1)

SELECT
    UF1.DR_Id
        ,STUFF(
                (SELECT
                    ',' + UF2.UF_Name
                FROM 
                    UploadedFiles UF2
                WHERE 
                    UF1.DR_Id = UF2.DR_Id
                ORDER BY 
                    UF2.UF_Name
                FOR XML PATH(''), TYPE
                ).value('.', 'varchar(max)')
                ,1,1,''
            ) AS UF_LinkedFiles
FROM 
    [dbo].UploadedFiles UF1
WHERE
    UF1.DR_Id = @DR_Id
    OR
    (@DR_Id IS NULL AND UF1.DR_Id = UF1.DR_Id)
GROUP BY 
    UF1.DR_Id

表: UploadedFiles - 每一行都是与 DR_Id 相关联的文件名的条目,该文件是外键。因此,有多个行具有相同的 DR_Id

以下是UploadedFiles的样子:

    UF_Id   UF_Name DR_Id   UF_CreatedOn    UF_ModifiedOn
10  20140617367742.jpg  1000    2014-06-17 20:24:33.507 2014-06-17 20:24:33.507
20  20140617365324.jpg  1000    2014-06-17 20:24:33.507 2014-06-17 20:24:33.507
30  20140618912322.jpg  1010    2014-06-18 11:11:48.547 2014-06-18 11:11:48.547
40  20140618396338.jpg  1020    2014-06-18 11:49:50.980 2014-06-18 11:49:50.980
50  20140618392387.jpg  1020    2014-06-18 11:49:50.980 2014-06-18 11:49:50.980
60  20140618394725.jpg  1020    2014-06-18 11:49:50.980 2014-06-18 11:49:50.980
70  20140618396338.jpg  1030    2014-06-18 11:52:01.770 2014-06-18 11:52:01.770
80  20140618392387.jpg  1030    2014-06-18 11:52:01.770 2014-06-18 11:52:01.770
90  20140618394725.jpg  1030    2014-06-18 11:52:01.770 2014-06-18 11:52:01.770
100 20140618396338.jpg  1040    2014-06-18 11:56:38.903 2014-06-18 11:56:38.903
110 20140618392387.jpg  1040    2014-06-18 11:56:38.903 2014-06-18 11:56:38.903
120 20140618394725.jpg  1040    2014-06-18 11:56:38.903 2014-06-18 11:56:38.903
130 20140618396338.jpg  1050    2014-06-18 11:57:46.803 2014-06-18 11:57:46.803

结果如下:

DR_Id   UF_LinkedFiles
1000    20140617365324.jpg,20140617367742.jpg
1010    20140618912322.jpg
1020    20140618392387.jpg,20140618394725.jpg,20140618396338.jpg
1030    20140618392387.jpg,20140618394725.jpg,20140618396338.jpg
1040    20140618392387.jpg,20140618394725.jpg,20140618396338.jpg
1050    20140618392387.jpg,20140618394725.jpg,20140618396338.jpg