现有一张表table字段 
     a      b
    1       a
    2       a
        1       b
    4       b
    5       b    1       c
    2       c
    6       c     1       d
     2      d
     2      d
如果我想以b分组,其中a字段中只包含1,2的值,而且只能包含1,2不能有别的纪录。譬如上边我
得到的是
  a      b
    1       a
    2       a     1       d
     2      d
     2      d
这个怎么查啊,请教各位大侠了,小弟刚出家不久,现在工作碰到。谢谢了
在线等啊!

解决方案 »

  1.   

    select *
    from (
    select 1 a, 'a' b from dual
    union all
    select 2 a, 'a' b from dual
    union all
    select 1 a, 'b' b from dual
    union all
    select 4 a, 'b' b from dual
    union all
    select 5 a, 'b' b from dual
    union all
    select 1 a, 'c' b from dual
    union all
    select 2 a, 'c' b from dual
    union all
    select 6 a, 'c' b from dual
    union all
    select 1 a, 'd' b from dual
    union all
    select 2 a, 'd' b from dual
    union all
    select 2 a, 'd' b from dual) T
    where T.a in (1,2)
      

  2.   


    select a,b
    from table
    where a=1 or a=2
    group by a,b
      

  3.   

    楼主要先以B分组.
    select a,b from yourtable where a=1 or a=2 group by b,a
      

  4.   

    楼上几位XD写的好像不符合需求 .. try it ..
    select *
      from tablename t1
     where not exists 
            (   
              select t2.b 
                from tablename t2
             where t2.a not in (1,2)
               and t1.b = t2.b
            );
             A B
    ---------- -
             1 a
             2 a
             1 d
             2 d
             2 d
      

  5.   

    mantisXF大哥,你写的结果正是我想要的,谢谢啦,我刚用这个论坛不久,以后有什么不懂的还请多多指教,呵呵