请教一个分组排序的问题?

 所属目录:Java   |   类型:技术问答   |   时间:2007-05-21
 问题:

有表结构如下  
   
  id   ,   content(内容)     ,sort(类别)  
  1                   aaa                         0  
  2                   bbb                         3  
  3                   ccc                         1  
  4                   ddd                         3  
  5                   ddd                         1  
  6                   rtre                       3  
  7                   dsdf                       3  
  8                   dsdf                       0  
  ....  
   
  想要得到如下结果集:  
   
   
  id   ,   content(内容)     ,sort(类别)  
   
  sort   为0的一个组  
  1               aaaa                         0  
  8               dsdf                         0  
   
  sort   为1的一个组  
  3               ccc                           1  
  5               ddd                           1  
   
  sort   为3的一个组  
  2                 bbb                         3  
  4                 ddd                         3  
  6                 rtre                       3  
  7                 dsdf                       3  
   
  如上所示要按sort来排序分组,每组最多4条记录,每组中又按id来排序  
  如何写sql语句?  
 

· 网友精彩回答:

发表者:zyvslxl

select   *   from   test1   as   a   where   id   in    
  (select     4   id   from   test1   c   where   c.sort   =  
  (select   sort   from   test1   b   where   a.sort   =   b.sort   and   a.sort=c.sort   group   by   sort     ))  
    order   by   a.sort,a.id  
   
  一个很垃圾的写法

发表者:zlp321002

--try  
  create   table   test(id       int   identity(1,1)   ,content   char(8),sort   int   )  
  insert   into   test   select   aaa,0  
  union   all   select   bbb,   3  
  union   all   select   ccc,   1  
  union   all   select   ddd,   3  
  union   all   select   ddd,   1  
  union   all   select   rtre,   3  
  union   all   select   dsdf,   3  
  union   all   select   dsdf,   0  
   
  select   id,content,sort   from   test    
  group   by   sort,content,id  
  having   count(*)<=4  
  order   by   sort,id  
   
   
  --  
  id                     content     sort                  
  -----------   --------   -----------    
  1                       aaa             0  
  8                       dsdf           0  
  3                       ccc             1  
  5                       ddd             1  
  2                       bbb             3  
  4                       ddd             3  
  6                       rtre           3  
  7                       dsdf           3  
   
   
   
 

发表者:zjcxc

select   *   from   表   a  
  where   id   in(  
          select   top   4   id   from   表   where   [sort]=a.[sort]   order   by   id)  
  order   by   [sort],id

发表者:631799

select   *   from   表   a   where   (select   count(1)   from   表   where   [sort]=a.[sort]   and   id<=a.id)<=4   order   by   [sort],id

.
处理 SSI 文件时出错
© 2006-2008 All Rights Reserved