row_number() over partition by 分组聚合
分组聚合,就是先分组再排序,可以的话顺手标个排名;如果不想分组也可以排名;如果不想分组同时再去重排名也可以
Oracle和SQL server的关键字是over partition by
mysql的无关键字row_number() over (partition by col1 order by col2),表示根据col1分组,在分组内部根据col2排序 需求:给username加上唯一标示id
背景:需要一个纬度表,里面有仅仅username的唯一标示,因为hive中不存在自增id 但是有弊端,如果最大值有多个,那么就会出现多个最大值,so,要动态的ROW_NUMBER() OVER(
[PARTITION BY column_1, column_2,…]
[ORDER BY column_3,column_4,…]
)-- 建表
USE db_03;
DROP TABLE IF EXISTS employee;
create table employee (empid int ,deptid int ,salary decimal(10,2));
insert into employee values(1,10,5500.00);
insert into employee values(2,10,4500.00);
insert into employee values(3,20,1900.00);
insert into employee values(4,20,4800.00);
insert into employee values(5,40,6500.00);
insert into employee values(6,40,14500.00);
insert into employee values(7,40,44500.00);
insert into employee values(8,50,6500.00);
insert into employee values(9,50,7500.00);
SELECT * FROM employee;SELECT *, Row_Number() OVER (partition by deptid ORDER BY salary desc) rank FROM employee
select distinct
price,
row_number() over (order by price)
from
products
order by
price;price | row_number
---------+------------
300.00 | 1
300.00 | 2
400.00 | 3
500.00 | 4
600.00 | 5
600.00 | 6
700.00 | 7
800.00 | 8
800.00 | 9
900.00 | 10
1100.00 | 11with prices as (
select distinct
price
from
products
)
select price,row_numer()over(order by price) from prices;price | row_number
---------+------------
300.00 | 1
400.00 | 2
500.00 | 3
600.00 | 4
700.00 | 5
800.00 | 6
900.00 | 7
1100.00 | 8select deptid,salary
from employee a
where 2 > (
select count(1)
from employee b
where a.salary<b.salary and a.deptid=b.deptid
)
order by a.deptid,a.salary desc;SET @row=0;
SET @groupid='';
select a.deptid,a.salary
from
(
select deptid,salary,case when @groupid=deptid then @row:=@row+1 else @row:=1 end rownum,@groupid:=deptid from employee
order by deptid,salary desc
)a
where a.rownum<=2;SELECT t.stuid,
t.stuname,
t.score,
t.classid
FROM stugrade t
where t.score = (SELECT max(tmp.score) from stugrade tmp where tmp.classid=t.classid)
最新文章
- 客户端的验证插件validator
- MySQL练习-employees数据库(二)
- log4j配置详解
- mongo基本操作
- Winform以任意角度旋转PictureBox中的图片的方法
- 设计模式学习之组合模式(Composite,结构型模式)(10)
- 【转】Linux终端下 dstat 监控工具
- ACM ICPC 2015 Moscow Subregional Russia, Moscow, Dolgoprudny, October, 18, 2015 D. Delay Time
- java简单统计.java文件中的有效代码行,空行,注释行
- HDU 2586 LCA
- Python-描述符
- HDU 1358 (所有前缀中的周期串) Period
- startkde出现$DISPLAY is not set or cannot connect to the X server
- C功底挑战Java菜鸟入门概念干货(二)
- uva311 - Packets(贪心)
- 应用程序写Xml文档
- 201521123064 《Java程序设计》第13周学习总结
- 【Git】CentOS7 通过源码安装Git
- 【Qt编程】Qt学习之窗口间的相互切换
- HDUOJ-2089 不要62