Sql比较逗号分隔值

时间:2013-08-14 15:13:39

标签: sql sql-server-2005

我正在寻找比较同一单元格中的值的方法。

现在我有一个查询得到的数据,输出如下:

ID|firstname|lastName|Gender|Tag
1 |Jo       |Sav     |b     |sport,computer,sport
2 |Franck   |Gag     |b     |climbing, swimming
3 |Oli      |Dann    |b     |cycling,running,cycling
4 |Alyss    |Baby    |g     |make up, cycling

我想要的只是获取在标记列中获取重复数据的人。

所以输出就像:

ID|firstname|lastName|Gender|Tag
1 |Jo       |Sav     |b     |sport,computer,sport
3 |Oli      |Dann    |b     |cycling,running,cycling

提前致谢!

编辑#1:人们想知道我的架构是怎样的。

ID|firstname|lastName|Gender|Tag
1 |Jo       |Sav     |b     |sport
2 |Franck   |Gag     |b     |climbing
3 |Oli      |Dann    |b     |cycling
4 |Alyss    |Baby    |g     |make up
1 |Jo       |Sav     |b     |computer
1 |Jo       |Sav     |b     |sport
2 |Franck   |Gag     |b     |swimming
3 |Oli      |Dann    |b     |cycling
3 |Oli      |Dann    |b     |running
...

1 个答案:

答案 0 :(得分:3)

你可以这样做。额外EXISTS子句检查ID是否存在于Tag重复的记录中。

SELECT  ID, firstname, lastName, Gender,
        STUFF((SELECT ',' + Tag
              FROM TableName
              WHERE ID = a.ID
              FOR XML PATH ('')) , 1, 1, '')  AS TagList
FROM    TableName AS a
WHERE   EXISTS
        (
            SELECT 1
            FROM tableName b
            WHERE b.ID = a.ID
            GROUP BY b.id, b.tag
            HAVING COUNT(*) > 1
        )
GROUP   BY ID, firstname, lastName, Gender