日期:2014-05-18  浏览次数:20618 次

求一SQL语句优化```
我表sub中有一个类别字段sortid,有个日期字段lastback,我现在想取每个类别的最新5条数据。然后再取前20条。
select   top   20   *   from   (
select   top   5   *   from   sub   where   isnull(isback,1)=0   and   sortid=1  
union   all  
select   top   5   *   from   sub   where   isnull(isback,1)=0   and   sortid=2  
union   all  
select   top   5   *   from   sub   where   isnull(isback,1)=0   and   sortid=3  
union   all  
select   top   5   *   from   sub   where   isnull(isback,1)=0   and   sortid=4  
union   all  
select   top   5   *   from   sub   where   isnull(isback,1)=0   and   sortid=5  
union   all  
select   top   5   *   from   sub   where   isnull(isback,1)=0   and   sortid=6  
union   all  
select   top   5   *   from   sub   where   isnull(isback,1)=0   and   sortid=7  
union   all  
select   top   5   *   from   sub   where   isnull(isback,1)=0   and   sortid=9)   a  
order   by   lastback   desc
但目前这方法好象太太太笨了。   。所以想优化一下。。请教高手。谢谢`!

------解决方案--------------------
select * from sub a where priamyKey in(select top 5 priamyKey from sub where sortid=a.sortid order by lastback desc)
order by sortid

priamyKey为主键.