1

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

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

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
...
4

1 回答 1

3

你可以这样做。extraEXISTS子句检查 是否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
于 2013-08-14T15:33:08.643 回答