一、case when
case when 函数可使用在group by语句后,进行条件分组
使用sum,count,avg等聚合函数和case when同时使用,可以将行结构数转换为列结构数据;
update条件分支里使用case when,更新工资问题;
case when 语句中可以使用between ,like,<,>,以及in,exist等子查询功能;
case when 本身值可作为条件再次嵌套case when语句中,如输出x,y,z三列中的最大值问题;
key x y z
1 3 4 5
2 6 4 3
3 5 7 5
4 5 2 3
select key,case when case when x>y then x else y end>z
then z
else case when x>y then x else y end
end as max_value
from table 1
二、自连接
使用自连接查找局部不一致的列:查找a列相同,b列不同的记录,延伸到同名不同姓,同课不同分等问题;
select * from table t1 inner join table t2 on
t1.a=t2.a and t1.b<> t2.b
非等值自然连接解决排序问题:
id score
1 100
2 80
3 95
4 85
5 85
select t1.score,(select count(t2.score) from table t2 where t2.score>t1.score)+1 as rank from table t1 order by rank; (跳过位次)
t1.score t2.score count(t2.score) rank
100 - 0 1
95 100 1 2
85 95,100 2 3
85 95,100 2 3
80 85,85,95,100 4 5
select t1.score,(select count(distinc t2.score) from table t2 where t2.score>t1.score)+1 as rank from table t1 order by rank; (不跳过位次)
t1.score t2.score count(distinct t2.score) rank
100 - 0 1
95 100 1 2
85 95,100 2 3
85 95,100 2 3
80 85,85,95,100 3 4