第一题
create table user_score
(logday date, -- 考试时间
userid VARCHAR(20), -- 考试用户
score int); -- 考试成绩Insert into user_score values
('2019-10-20',11111,85)
,('2019-10-20',22222,83)
,('2019-10-20',33333,86)
,('2019-10-21',11111,87)
,('2019-10-21',22222,65)
,('2019-10-21',33333,98)
,('2019-10-22',11111,67)
,('2019-10-22',22222,34)
,('2019-10-22',33333,88)
,('2019-10-23',11111,99)
,('2019-10-23',22222,33);
1)使用 over() 函数进行数据统计, 统计每个用户及表中数据的总数(要求相同用户排列在一起)
SELECT
* ,
count( userid ) over ( PARTITION BY userid ORDER BY userid) AS total
FROM user_score
2)求用户明细并统计每个用户的平均测试成绩(要求小数点后保留两位)总数
SELECT
* ,round(avg( score ) over ( PARTITION BY userid ),2) AS avg_score
FROM user_score
3)统计每一个用户的本次考试成绩和他上次的考试成绩(提醒用 first_value或lag函数)
实现方式一(使用lag函数)
SELECT logday,userid,score, lag( score,1 ) over ( partition BY userid order by logday rows BETWEEN unbounded preceding AND current ROW ) AS pre_score
FROM user_score
实现方式二(使用first_value函数)
SELECT
logday,userid,score, first_value(score) over ( partition BY userid order by logday
rows BETWEEN 1 preceding AND current ROW ) AS pre_score
FROM user_score
4) 计算每个用户最大的考试成绩(提醒:使用rank函数)
selectt.logday,t.userid,t.scorefrom( SELECT logday,userid,score,rank() over ( partition BY userid order by score desc ) AS sorted FROMuser_score) t where t.sorted = 1;
第二题
SELECT c.id, c.name,