s524141771 发表于 2013-1-12 16:20:39

读书笔记 SQL cookbook 2

1. order by sal desc/asc
   order by 3 desc/asc   -- 编号由1开始
   --------------------------------------------------------------------------------
2. order by deptno asc,sal desc
    注:可按select 表中没有的列排序,若有group by 或 distinct 可能不行。
--------------------------------------------------------------------------------   
3. 子串排序
    select ename,job from emp order by substr(job,length(job)-2)--index 从一开始
                                       substring(job,len(job)-2,2) --sqlserver
--------------------------------------------------------------------------------
4. 字母数字混合 如: data: tony20
   思路:得到字母或者数字。
   如按数字:
   postgreSQL + oracle: selectdata from v
          order by replace(data,
                              replace(
                                 translate(data,'0123456789','#########'),
                                                                         '#',''),'')
   按字串:
          select * from v
            order by replace(translate(data,'0123456789','##########'),'#','')
   tips:TRANSLATE(string,from_str,to_str)
       返回将(所有出现的)from_str中的每个字符替换为to_str中的相应字符以后的string
      to_str不能为空。Oracle将空字符串解释为NULL,并且如果TRANSLATE中的任何参数为NULL,那么结果也是NULL。            
   TRANSLATE   ( 'please   go   away ',   'a ',   NULL)   ==>   NULL
   TRANSLATE   ( 'grumpy   old   possum ',   'uot ',   '%$* ')   ==>       'gr%mpy   $ld   p$ss%m '                                                               
msql:暂不支持:translate
   --------------------------------------------------------------------------------
5.处理排序的null在前还是后
   mysql + oracle 8i之前:
         select ename,sal,comm,is_null
            from (select ename,sal,comm,case when comm is null then 0 else 1 end as is_null from emp) x
            order by is_null ,commdesc;
   oracle 9i及以后:
         select ename,sal,comm from emp order by commNULLS FIRST / NULLS LAST   

--------------------------------------------------------------------------------         
6.根据某些条件逻辑来排序:
      如JOB 是salesman则按comm排序,否则按sal排序
      select ename,sal,job,comm from emp
         order by case when job='salesman' then comm
                  else sal
                  end
      也可:
      select ename,sal,job,comm,
                   case when job='salesman' then comm
                   else sal
                   end
      from emp order by 5;
页: [1]
查看完整版本: 读书笔记 SQL cookbook 2