表具有唯一的行,但是如何查找某些列的重复项?

时间:2013-04-30 15:36:37

标签: sql oracle

我的表格如下所示:

ID         TID        TNAME     CID     CNAME     SEQUENCE
-----------------------------------------------------------
200649     6125     Schalke    356954   Mirko         1
200749     6125     Schalke    356954   Mirko         1
200849     6125     Schalke    439386   Fred          1
200849     6125     Schalke    356954   Mirko         1
200849     6125     Schalke    495881   Michael       1
200949     6125     Schalke    401312   Felix         1
200949     6125     Schalke    495881   Michael       2

我想查询此表,只有在ID和SEQUENCE重复时才会返回。即它应该只返回:

200849     6125     Schalke    439386   Fred          1
200849     6125     Schalke    356954   Mirko         1
200849     6125     Schalke    495881   Michael       1

我使用过having count(ID) > 1但它不会返回任何内容,因为CID都是唯一的。

感谢您的帮助!

3 个答案:

答案 0 :(得分:3)

我认为这是一种方法:

select a.*
from yourTable as a
inner join (
    select id, sequence 
    from yourTable 
    group by id, sequence 
    having count(id)>1) as b on a.id = b.id and a.sequence=b.sequence

答案 1 :(得分:2)

这样的东西?

SELECT b.id, 
       b.tid, 
       b.tname, 
       b.cid, 
       b.cname, 
       b.sequence 
FROM   (SELECT id, 
               sequence, 
               Count(*) CNT 
        FROM   table1 
        GROUP  BY id, 
                  sequence 
        HAVING Count(*) > 1) a 
       LEFT JOIN table1 b 
              ON b.id = a.id 
                 AND b.sequence = a.sequence 

<强>结果

|     ID |  TID |   TNAME |    CID |   CNAME | SEQUENCE |
---------------------------------------------------------
| 200849 | 6125 | Schalke | 439386 |    Fred |        1 |
| 200849 | 6125 | Schalke | 356954 |   Mirko |        1 |
| 200849 | 6125 | Schalke | 495881 | Michael |        1 |

See the demo

答案 2 :(得分:2)

我喜欢将解析函数用于这些事情:

select t.*
from (select t.*, count(*) over (partition by id, sequence) as cnt
      from t
     ) t
where cnt > 1

这也为您提供输出中每行的重复数量。