一张表t1
有a,b,c,d 四列取值可能如下:
a  b  c        d
0 一  100   a1
1 一  200   a1
2 二  300   a2
3 二  400   a2
要查询:
对于某个d值,
如果存在a=0的行,那么当b是"一"时取出c>50且a=0的行,b是"二"时取出c>100且a=0的行;
如果不存在a=0的行,那么当b是"一"时取出c>50且MAX(c)的行,b是"二"时取出c>100且MAX(c)的行; 如上表应该取得以下两行:
a  b  c        d
0 一  100   a1
3 二  400   a2这个SQL如何写呢?

解决方案 »

  1.   

    select * from tb 
     where a=0 
       and c>(case when b='一' then 50
                   when b='二' then 100)
    union all
    select a,b,c,d
    from (select x.*,row_number()(PARTITION BY d,b ORDER BY c desc) rn
            from  tb x
             and a <> 0 
             and c>(case when b='一' then 50
                         when b='二' then 100)
             and not exists(select distinct d from tb y where a=0 and x.d = y.d)
          ) z
    where rn = 1
      

  2.   

    select * from tb  
     where a=0  
       and c>(case when b='一' then 50 
                   when b='二' then 100) 
    union all 
    select * from tb
     where a  <> 0  
       and c>(case when b='一' then 50 
                   when b='二' then 100) 
    and c=(select max(tbb.c) from tbb)