Devolver registros con todas las columnas pero con una única de ellas (distinta)

I have like 20 columns in my DB. I would need to select only those with distinct Ref_ID but if I use distinct(ref_ID), I get only list of these values. I would need to retrieve all columns, e.g. all records but with distinct ref_id.
Estoy usando Oracle 9g.
E.g. there are 10 records five of which have the same ref_id. So the select should return only these 5 records with all columns.

preguntado el 03 de mayo de 12 a las 07:05

Probably should give an example. Hard to tell what you mean. -

distinct(ref_ID), col1, col2, col3, ... -

So multiple records exist with the same Ref_ID? From which record do you then want to retrieve the other columns? And which SQL dialect are you using? -

3 Respuestas

Prueba esto: 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

Fecha:

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

Salida:

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

contestado el 03 de mayo de 12 a las 08:05

Hard to tell what you mean, but here is an idea, this will return the REF_ID values that your table includes more than once:

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

contestado el 03 de mayo de 12 a las 08:05

Fair's fair, your answer beat my pretty much identical one by four seconds, let's go with yours :) - user743382

Otra solución:

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
      ) 

contestado el 03 de mayo de 12 a las 08:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.