MYSQL order 、group 与row_number详解
一、order by
order by A ASC, B DESC,C ASC …
上述语句会先按照A排序,当A相同的时候再按照B排序,当B相同的再按照C排序,并会不按照ABC组合一起排序
二、group by
group by A,B,C…
select 中的字段必须是group by中的字段,但是聚合函数中的参数字段没有必须出现在 group by中
select A , B ,count(*) from t1 group by A,B,C
select A , B ,C,count(*) from t1 group by A,B,C
select A , B ,count(C) from t1 group by A,B,C
# 语法错误,应该使用having
select A , B ,count(C) as countABC from t1 where countABC >3 group by A,B,C
select A , B ,count(C) as countABC from t1 having countABC >3 group by A,B,C select A , B ,count(C) from t1 group by A,B,Cselect A ,count(*) from t1 group by A 与 select A ,count(A) from t1 group by A
与
select A ,count(B) from t1 group by A 效果一致select A ,count(distinct B) from t1 group by A
与
select A ,B,count(*) from t1 group by A ,B 效果一致select A ,sum(B) from t1 group by A
select A ,max(B) from t1 group by A
select A ,min(B) from t1 group by A
三、row_number 窗口排名函数
row_number() over ( [partition by column] order by order_expression [asc|desc]) as ranking
该方法常用于排名、连续登陆数统计,部门业绩排名
row_number 无并列排名,强制连续序号 例如 1,2,3
rank 允许并列排名,后续序号不连续 例如 1,1,3
dense_rank() 允许并列排名,后续序号连续 例如 1,1,2
count(*) 统计所有行数,包括NULL
count(column) 统计column字段非NULL的行数