返回包含所有列但具有唯一其中一列的记录(不同)

时间:2012-05-03 06:42:54

标签: sql oracle

我的数据库中有20列。我只需要选择具有不同Ref_ID的那些,但如果我使用distinct(ref_ID),我只得到这些值的列表。我需要检索所有列,例如所有记录但具有不同的ref_id 我使用的是Oracle 9g 例如。有10条记录,其中五条具有相同的ref_id。所以select应该只返回所有列的这5个记录。

3 个答案:

答案 0 :(得分:3)

试试这个:http://www.sqlfiddle.com/#!4/9f1ae/10

select *
from
(
  select rank() over(partition by d_let order by d_num) rank, tbl.*
  from tbl
  order by d_let
) x
where x.rank = 1 -- only the first row among duplicates

数据:

CREATE TABLE tbl
    (d_let varchar2(1), d_num int)
/
INSERT ALL
    INTO tbl (d_let, d_num)
         VALUES ('a', 1)
    INTO tbl (d_let, d_num)
         VALUES ('a', 2)
    INTO tbl (d_let, d_num)
         VALUES ('a', 3)
    INTO tbl (d_let, d_num)
         VALUES ('b', 6)
    INTO tbl (d_let, d_num)
         VALUES ('b', 3)
    INTO tbl (d_let, d_num)
         VALUES ('c', 2)
    INTO tbl (d_let, d_num)
         VALUES ('c', 3)
    INTO tbl (d_let, d_num)
         VALUES ('c', 5)
    INTO tbl (d_let, d_num)
         VALUES ('c', 6)
    INTO tbl (d_let, d_num)
         VALUES ('c', 4)
SELECT * FROM dual

输出:

RANK        D_LET   D_NUM
1           a       1
1           b       3
1           c       2

答案 1 :(得分:2)

很难说出你的意思,但这是一个想法,这将返回你的表不止一次包含的REF_ID值:

select * from YOUR_TABLE
where REF_ID in(
    select REF_ID from YOUR_TABLE
    group by 
      REF_ID
    having
      count(REF_ID) > 1)

答案 2 :(得分:0)

另一种解决方案:

SELECT * 
FROM TableX t
WHERE EXISTS
      ( SELECT *
        FROM TableX tt
        WHERE tt.REF_ID = t.REF_ID
          AND tt.PK <> t.PK           --- the Primary Key of the table
      ) 
相关问题