SQL Puzzle

1. 按条件分块取数据

有表A(CD),数据为

要求:当有CD为0的记录时,取得结果为0,

           当表中没有CD=0的记录时,取得的结果为1,2,3(将CD<>0的记录都取出来)

可行SQL脚本:

select * from test where cd = '0'
union
select * from test t where cd <> '0' and not exists
 (select * from test t where cd = '0' group by cd having count(*) > 0)

2. Top N 

select *
from employee e1
where (select count(distinct e2.salary)
from employee e2
where e2.salary > e1.salary) = (N-1)
 
原文地址:https://www.cnblogs.com/dufu/p/7505105.html