有张表 tb_a 其中有 3 个字段 a,b,ctime
a 唯一,b有重复,ctime为时间字段
现在想找按ctime倒序排序的,其中b唯一的 10条记录,该怎么写SQL语句?

解决方案 »

  1.   

    select a,b,ctime
      from (select a,b,ctime,row_number() 
                   over(partition by b order by ctime desc nulls last) rn
              from tb_a
           )
     where rn=1;
      

  2.   

    b唯一是什么意思?如果有两条记录b值都为 'aaa',
    是不是这两条记录都不包含在结果中,即使该ctime字段值排在前10位?
    如果是:select * from (
    select * from tb_a,
    (select b from tb_a group by b having count(1)=1) c
    where a.b=c.b order by ctime desc) where rownum<11;
      

  3.   

    不就是要按ctime倒序排序吗?
    select * from tb_a order by ctime desc;
      

  4.   

    b如何做到唯一呢?。。  因为你的b是有重复的, 如果在相同的b的情况下,取最大的ctime  还是取最小的ctime??
      

  5.   


    --楼主的意思应该是先取没有重复值的b,然后再按ctime倒序
    select a,b,ctime
    from tb_a
    where b in (select b from tb_a group by b having count(*) = 1) 
    order by ctime desc