关于ORDER BY 指定排列顺序

来源:互联网 发布:德利迅达银川大数据 编辑:程序博客网 时间:2024/04/28 21:23

*如何让ORDER   BY按指定的顺序排序     
      
  表a里有个列叫Type,是商品类别,就3种情况:S,A,B,如下:   
  id   name   type     
  1     一班   S     
  2     五班   A     
  3     三班   B     
  4     四班   B     
  5     二班   A     
  6     六班   S     
  现在我需要按照‘S’,‘A’,‘B’的顺序排序,如下:   
  1   一班   S     
  6   六班   S     
  5   二班   A     
  2   五班   A     
  3   三班   B     
  4   四班   B     
    
  SELECT   *   
  FROM   tbl_test   
  ORDER   BY   "@#$$%#$%@$@#$@$@#@$这里应该咋写?"   

      
  表a里有个列叫Type,是商品类别,就3种情况:S,A,B,如下:   
  id   name   type     
  1     一班   S     
  2     五班   A     
  3     三班   B     
  4     四班   B     
  5     二班   A     
  6     六班   S     
  现在我需要按照‘S’,‘A’,‘B’的顺序排序,如下:   
  1   一班   S     
  6   六班   S     
  5   二班   A     
  2   五班   A     
  3   三班   B     
  4   四班   B     
    
  SELECT   *   
  FROM   tbl_test   
  ORDER   BY   "@#$$%#$%@$@#$@$@#@$这里应该咋写?"   */

      
  
select   *   from   a   where   type='S'   union   all   
  
select   *   from   a   where   type='A'   union   all   
  
select   *   from   a   where   type='B'       
  
select   id   ,   name   ,type   
  
from   a   
  
order   by   case   type   when   'S'   then   1   
  
when   'A'   then   2   when   'B'   then   3   else   4   end   (如果对ID排序,则加最后加,id)       
  
select   id   ,   name   ,type   
  
from   (select   *,   case   type   when   'S'   then   1   when   'A'   then   2   else   3   end   as   seq   from   a)   X   
  
order   by   seq       
  
--上诉对ID列没有进行排序,如果在上诉基础上对ID再进行排序。   
  select   id   ,   name   ,type(假设有列id   ,name,   type)   
  
from   (select   *,   case   type   when   'S'   then   1   when   'A'   then   2   else   3   end   as   seq   from   a)   X   
  
order   by   seq,id     
  
/*1   一班   S     
  6   六班   S     
  2   五班   A     
  5   二班   A     
  3   三班   B     
  4   四班   B     
*/

原创粉丝点击