原表:
Q1:求出每个学生最高的分数:
SELECT stu,MAX(sc) FROM yasi GROUP BY stu;#成功
Q2:求出每个学生的考试次数:
SELECT stu,COUNT(1) FROM yasi GROUP BY stu;#成功
Q2:求出每个学生最近一次考试的成绩:
SELECT stu,MAX(tm),sc FROM yasi GROUP BY stu;#失败,max(time)是正确的,但对应的sc不正确。
这个就不对了,日期和分数对不上!
所以要用窗口函数:
##要用窗口函数
SELECT *, row_number() over(PARTITION BY stu ORDER BY tm DESC) rank FROM yasi WHERE rank = 1;
#报错 #新生成的rank字段,无法直接筛选
SELECT * FROM
(SELECT *,row_number() over(PARTITION BY stu GROUP BY tm DESC) rank FROM yasi)
WHERE rank = 1;#正确
变形1,可以开多个窗口(partition by 后跟多个字段)
变形2,任意抽取每组的两条记录怎么抽。只要在窗口函数中order by 后面加rand()即可。以随即顺序排序,太绝了!
#得到不同id type下的score前两名
SELECT * FROM
(SELECT *, row_number() over(PARTITION BY app_id,tp ORDER BY score DESC) rank FROM app)
WHERE rank <= 2;#开了多个窗口,app_id和tp
#得到不同id type下score,随即抽两个
SELECT * FROM
(SELECT *,row_number() over(PARTITION BY app_id,tp ORDER BY RAND()) rank FROM app)
WHERE rank <= 2;