0

我不明白如何编写一个简单的 sql 语句,它只显示那些出现多次的条目。

前任

NodeID  Number

0       12
1       12
2       12
0       13
1       13
0       14
1       15
2       16
1       17

选择nodeIDnumber从表中出现多次不同的数字nodeID

结果:

NodeID  Number
0       12
1       12
2       12
0       13
1       13
4

4 回答 4

3
SELECT  a.*
FROM    TableName a
        INNER JOIN
        (
            SELECT  Number
            FROM    TableName
            GROUP   BY Number
            HAVING  COUNT(*) > 1
        ) b ON a.Number = b.Number

另一种方法是使用EXISTS

SELECT  a.*
FROM    TableName a
WHERE   EXISTS
        (
            SELECT  1
            FROM    TableName b
            WHERE   a.Number = b.Number
            GROUP   BY Number
            HAVING  COUNT(*) > 1
        ) 
于 2013-04-20T11:14:57.797 回答
0

尝试这个

SELECT NodeID , Number FROM TableName WHERE Number IN
(SELECT Number FROM TableName  GROUP BY Number HAVING  COUNT(*) > 1)
于 2013-04-20T11:17:33.263 回答
0

我的第一个想法是像下面这样进行自我加入,但它不起作用,因为分组发生在之后。

SELECT T1.NodeId, T2.Number, COUNT(T2.Number) C FROM Table T1 INNER JOIN Table T2 USING(Number) WHERE C > 1 GROUP BY T2.Number

因此,您必须先进行分组选择,然后进行连接:

SELECT NodeId, Number
FROM Table T1
INNER JOIN (
     SELECT Number, COUNT(Number) C
     FROM Table
    WHERE C > 1
    GROUP BY Number
) T2 USING(Number)
于 2013-04-20T11:20:23.483 回答
0

您也可以EXISTS不使用GROUP BY

SELECT nodeid, 
       number 
FROM   Table1 t1 
WHERE  EXISTS(SELECT 1 
              FROM   Table1 t2 
              WHERE  t1.number = t2.number 
                     AND t1.nodeid <> t2.nodeid) 

演示

于 2013-04-20T11:18:45.847 回答