1.在WHERE子句中引用别名列1.1.当表里的某些列没有被恰当命名的时候,这个技巧尤其有用1.2.sql

select sal as salary, comm as commission  from emp where salary < 5000

1.3.内嵌视图1.3.1.sql

select *   from ( select sal as salary, comm as commission   from emp        ) x  where salary < 5000

1.3.2.聚合函数1.3.3.标量子查询1.3.4.窗口函数1.3.5.别名2.CONCAT函数2.1.串联多列的值2.2.在DB2、Oracle和PostgreSQL 中,“||”是CONCAT函数的快捷方式2.3.在SQL Server中则为“+”3.随机返回若干行记录3.1.如果ORDER BY子句使用数值常量,那么就需要按照SELECT列表里的顺序来排序3.2.如果ORDER BY子句使用了函数,那么就需要按照该函数的返回值来排序,而函数返回的值是根据结果集里的每一行计算而来的3.3.MySQL3.3.1.sql

  select ename,job from emp  order by rand() limit 5

3.4.PostgreSQL3.4.1.sql

 select ename,job   from emp  order by random() limit 5

3.5.Oracle3.5.1.sql

 select *   from (  select ename, job    from emp   order by dbms_random.value()        )   where rownum <= 5

3.6.SQL Server3.6.1.sql

select top 5 ename,job   from emp  order by newid()

4.把Null值转换为实际值4.1.COALESCE函数4.1.1.sql

select coalesce(comm,0)   from emp

4.1.2.更方便、更简洁4.2.CASE4.2.1.sql

 select case       when comm is not null then comm       else 0       end  from emp

4.3.适用于所有的数据库5.依据子串排序5.1.按照职位字段的最后两个字符对检索结果进行排序5.2.DB2、MySQL、Oracle和PostgreSQL5.2.1.sql

select ename,job  from emp order by substr(job,length(job)-2)

5.3.SQL Server5.3.1.sql

select ename,job  from emp order by substring(job,len(job)-2,2)

6.排序时对Null值的处理6.1.Oracle能够让你在无须修改非Null值数据的情况下方便地把Null值排到最前面或者最后面,其他数据库得添加一个辅助列6.1.1.Oracle 9i及后续版本NULLS FIRST和NULLS LAST来决定Null值应该排到前面还是后面6.2.辅助列6.2.1.只存在于查询语句里,而不存在于表中6.2.2.目的是让你能够识别出Null值,并控制其排在最前面还是最后面6.3.对于非Oracle解决方案的查询语句,其内嵌视图X会返回如下结果集6.4.sql

select ename,sal,comm,       case when comm is null then 0 else 1 end as is_null  from emp

6.5.ENAME SAL COMM IS_NULL


SMITH 800 0
ALLEN 1600 300 1
WARD 1250 500 1
JONES 2975 0
MARTIN 1250 1400 1
BLAKE 2850 0
CLARK 2450 0
SCOTT 3000 0
KING 5000 0
TURNER 1500 0 1
ADAMS 1100 0
JAMES 950 0
FORD 3000 0
MILLER 1300 0

7.依据条件逻辑动态调整排序项7.1.如果JOB等于SALESMAN,就要按照COMM来排序;否则,按照SAL排序7.2.sql

select ename,sal,job,comm   from emp  order by case when job = 'SALESMAN' then comm else sal end

7.3.sql

select ename,sal,job,comm,       case when job = 'SALESMAN' then comm else sal end as ordered from emporder by 5

7.4.ENAME SAL JOB COMM ORDERED


TURNER 1500 SALESMAN 0 0
ALLEN 1600 SALESMAN 300 300
WARD 1250 SALESMAN 500 500
SMITH 800 CLERK 800
JAMES 950 CLERK 950
ADAMS 1100 CLERK 1100
MARTIN 1250 SALESMAN 1300 1300
MILLER 1300 CLERK 1300
CLARK 2450 MANAGER 2450
BLAKE 2850 MANAGER 2850
JONES 2975 MANAGER 2975
SCOTT 3000 ANALYST 3000
FORD 3000 ANALYST 3000
KING 5000 PRESIDENT 5000