0

I have the following table: ID1 , ID2, Name, Sex

In the table there are records with duplicate ID1 but different ID2,name and sex -- Also there are records with duplicate ID2 and different ID1,Name and sex. Both ID1 and ID2 can have null values but not for same entry. I need to select non duplicate record for id1 and id2 e.g.

id1   id2      name    sex
10     null    jack     M
10     null    tom      M
null   40      jennie   F
null    32     jenie    F
null    32     emma     M
10     null    stevie   M

Need a select query to return:

id1   id2     name     sex
10     any    any      any (any means it can be either jack,tom,stevie)
null   40     jennie   F
null   32     any      any2 (any2 meaning jeniw or emma)
4

1 回答 1

2

You could use an EXISTS in your WHERE clause:

select t1.id1,
  t1.id2,
  name,
  sex
from yourtable t1
where exists (select *
              from yourtable t2
              where t1.id1 = t2.id1
               or t1.id2 = t2.id2)
group by t1.id1, t1.id2

See SQL Fiddle with Demo

于 2012-08-27T22:58:32.590 回答