oracle高级查询
按照指定顺序排序
使用场景:需要查询捆号为10,23,9...的数据,查询结果也是按照输入的顺序排列
sql:
select * from store
where xh in (10,23,9)
order by case xh
when 10 then 1
when 23 then 2
when 9 then 3
end
分组查询,查询每组的第一条或者最低值
- 场景:查询出每个部门工资最低的员工编号【每个部门可能有两个最低的工资员工】
查询结果:
--row_number() 顺序排序
select row_number() over(partition by deptid order by salary) my_rank ,deptid,USERID,salary from tsaler;
--rank() (跳跃排序,如果有两个第一级别时,接下来是第三级别)
select rank() over(partition by deptid order by salary) my_rank,deptid,USERID,salary from tsaler;
--dense_rank()(连续排序,如果有两个第一级别时,接下来是第二级)
select dense_rank() over(partition by deptid order by salary) my_rank,deptid,USERID,salary from tsaler;
1> 中间查询结果
分析:先按照重量类型分组,在按照时间排序给记录加上序号
select
ROW_NUMBER() OVER(PARTITION BY WEIGHTTYPE ORDER BY CREATEDATE DESC) rn,
t.*
from J_SITE_OPRATE_T t
where MATCHID='00017122500002'
select * from (
select
ROW_NUMBER() OVER(PARTITION BY WEIGHTTYPE ORDER BY CREATEDATE DESC) rn,
t.*
from J_SITE_OPRATE_T t
where MATCHID='00017122500002'
) t2
where t2.rn=1
row_number给每一组的记录添加序号(1,2,3...)。rank()给每一组添加序号,按照partition分组,然后根据order by后面的值(a)的大小决定序号的值,如果a相等,则序号相等