表没有主键,ID,code非空,code值只能是0或1 假设数据如下
ID     CODE
A        0
A        0
B        1
B        1
C        0
C        1
D        1
D        1
D        0要求选出 code字段既有 code=1 又有 code=0 的相同一类ID的数据期望结果:
ID     CODE
C        0
C        1
D        1
D        1
D        03Q~~~~~~~~~~~~~

解决方案 »

  1.   

    select id,code from tbl a where exists(select id,code from tbl b a.id =b.id and a.code<>b.code);
      

  2.   

    select id,code from tbl a where exists(select id,code from tbl b where a.id =b.id and a.code <>b.code);
    少了个where
      

  3.   

    with temp as(
              select 'A' id,0 code from dual
         union all
              select 'A' id,0 code from dual
         union all
              select 'B' id,1 code from dual
         union all
              select 'B' id,1 code from dual
         union all
              select 'C' id,0 code from dual
         union all
              select 'C' id,1 code from dual
         union all
              select 'D' id,1 code from dual
         union all
              select 'D' id,1 code from dual
         union all
              select 'D' id,0 code from dual     
    )
    select * from temp where id in(
    select id from(
    select id,code from temp group by id,code order by id
    ) group by id having count(id) >=2
    ) order by id
      

  4.   


    呵呵,执行不了,不知道是不是DB2的原因? 晚上用Oracle试试,现在没条件。基本思路也是对的,但是这样你会过滤掉那2个D 1的数据
      

  5.   


    借用3楼的数据测试了下,似乎没有过滤掉。不过我没有order by倒是真的SQL> with tbl as(
      2            select 'A' id,0 code from dual
      3      union all
      4            select 'A' id,0 code from dual
      5      union all
      6            select 'B' id,1 code from dual
      7      union all
      8            select 'B' id,1 code from dual
      9      union all
     10            select 'C' id,0 code from dual
     11      union all
     12            select 'C' id,1 code from dual
     13      union all
     14            select 'D' id,1 code from dual
     15      union all
     16            select 'D' id,1 code from dual
     17      union all
     18            select 'D' id,0 code from dual
     19  )
     20  select id,code from tbl a where exists(select id,code from tbl b where a.id =b.id and a.code <>b.code);ID       CODE
    -- ----------
    C           1
    C           0
    D           0
    D           1
    D           1
      

  6.   

    满足呀,两条都存在a.code<>b.code啊。
      

  7.   

    ID      CODE 
    -- ---------- 
    D          0 
    D          1 
    D          1
    这2条红色数据时怎么处理的呢?
      

  8.   

    我觉得你的SQL运行出来应该是
    ID      CODE 
    -- ---------- 
    C          1 
    C          0 
    D          0 
    D          1 少一条D   1…………
      

  9.   

    扫描到第一个D 1,存在 D0满足,加
    扫描到第二个D 1,存在D0满足,加。
      

  10.   

    select unique * from test t where 
    exists(select distinct(e.code) from test e where t.code<>e.code and e.id=t.id)