1

如果我跑

SELECT somecolumn FROM sometable GROUP BY somecolumn HAVING count(*) > 1;

输出将具有在somecolumn中多次出现的值sometable

但我想查看这些重复值出现的行(或其中的一部分)。例如,如果foobar是感兴趣的其他列的名称,sometable则输出的前几行可能看起来像

 somecolumn |  foo   |  bar
-------------------------------
 123        | foo_1  | bar_2
 123        | foo_3  | bar_5
 123        | foo_7  | bar_11
 234        | foo_13 | bar_17
 234        | foo_19 | bar_23
...

等等

我怎样才能做到这一点?

4

2 回答 2

2

对于与数据库无关的解决方案,您可以这样做:

SELECT *
FROM sometable S
WHERE somecolumn IN (   SELECT somecolumn 
                        FROM sometable 
                        GROUP BY somecolumn 
                        HAVING count(*) > 1)

对于 SQL Server 2005+,您可以这样做:

;WITH CTE AS
(
    SELECT  *,
            N = COUNT(*) OVER(PARTITION BY somecolumn)
    FROM sometable
)
SELECT *
FROM CTE
WHERE N > 1
于 2013-04-17T20:19:08.327 回答
0

您需要将这些列添加到选择以及分组中

SELECT 
    somecolumn, 
    foo, 
    bar 
FROM 
    sometable 
GROUP BY 
    somecolumn, 
    foo, 
    bar 
HAVING count(*) > 1;
于 2013-04-17T20:17:45.013 回答