SQL分组统计

全国各省份人口数排前三的城市
思路:先按照省份分组,再组内按照人口数排序取前三

set @num = 0, @class = ''; select * from ( select p.*, @num := if(@class=province, @num+1,1) as rank, @class := p.province as pclass from population as p order by province, popu desc )temp where rank < 4;

postgreSQL有比较简洁的用法
select *from ( select p.*, row_number() over(partition by province order by popu desc) as rank from population p ) temp where temp.rank < 4

【SQL分组统计】一周内用户登录次数统计
思路:调整日期格式,where筛选7天内的数据
select date(ctt) cttd, count(*) from login where date(ctt) > date_sub(curdate(), interval 7 day) group by cttd order by cttd;

    推荐阅读