`
wangyanlong0107
  • 浏览: 481214 次
  • 性别: Icon_minigender_1
  • 来自: 沈阳
社区版块
存档分类
最新评论

在union all中使用order by 报错的解决方案

 
阅读更多

//解法一:   
select * from (     
       select col_1,col_2,col_3,status     
       from t     
       where status >= 0     
       order by status)     
union all     
select * from (     
       select col_1,col_2,col_3,status     
       from t     
       where status < 0     
       order by status)     
/     
COL_1  COL_2   COL_3      STATUS     
------ ------- ------ ----------     
花生   瓜子    绿豆            0     
芍药   牡丹    月季            1     
优乐美 香飘飘  炸鸡            2     
牙膏   牙刷    杯子            3     
china  america canada         -1    
//解法二:   
select * from t    
order by    
      decode(status,   
             -1,1,   
             3,2,   
             2,3,   
             1,4,   
             0,5) desc   
/   
//这可是一个很妙的排序,本人首次看到在order by语句中可以使用decode()函数来排序   
//同理,我们也可以使用case语句来排序:   
//解法三:   
select * from t    
order by    
      case status   
      when -1 then 5   
      when 3 then 4    
      when 2 then 3    
      when 1 then 2    
      else 1   
      end    
/   
//union 和union all中都支持order by和group by排序和分组子句

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics