牛客网SQL刷题笔记
1,having score >avg(score) 会报错。因为score是一列数,而avg(score)是一个数,没法比较
同理:要筛选满足对于用户,它的所有记录分数都大于85的用户
group by uid
having score > 85 #会报错
group by uid
having min(score) >= 85 #这样才对
2,活跃天数的统计:同时对用户名与日期进行一起去重
count (distinct uid,date_format(submit_time,‘%Y%m%d’))
3,日期改格式:
date_format(submit_time,‘%Y%m’)
5,统计某列中不为空的值个数:count(列名)
统计某列中为空的个数:if(列名 is null, 1, null)
内容组合:
7,在union 中,order by 只放在最后,即union前表带order by 会报错
如果想要排列好的两个表再上下合并,这样改
select * from (原上表 可带order by)
union
select * from (原下表 可带order by)
8,时间间隔用submit_time - start_time 会报错
timestampdiff(second,start_time,submit_time) 这样才对
9,
SQL134
不明白下面这个为啥错了????
select er.uid,count(er.submit_time) as exam_cnt ,count(pr.submit_time) as question_cnt
from exam_record er left join practice_record pr on er.uid = pr.uid
where er.uid in
(select er.uid
from user_info ui join exam_record er on ui.uid = er.uid
join examination_info ei on er.exam_id = ei.exam_id
where ei.tag = 'SQL' and ei.difficulty = 'hard' and ui.level = 7
group by ui.uid
having avg(er.score) >80 )
and year(er.submit_time) = 2021
and year(pr.submit_time) = 2021
10,要完成三个表之间的全连接的两种方法:
——1、以user为主表进行连接(表1 right join 主表 left join 表2);
——2、用union all来完成表1和表2这两个表的全连接
11,
区分窗口函数中的partition by 与order by 是不一样的。order by 是对整体分组,分组后的聚合函数可以用在窗口函数的表达式里面,而partition by是仅仅针对窗口函数分的组
例子见SQL136
12,SQL137
1,交卷时间-作答时间 的时间差
timestampdiff(minute,start_time,submit_time)
2,第二快与第二慢 排序
row_number() over (partition by 试卷名 order by 时间差 desc) as dr1
row_number() over (partition by 试卷名 order by 时间差 asc) as dr2
dr1为2即第二快,dr2为2即为第二慢
3,第二快与第二慢用时之差 (不一定在同一列,不能直接减)
sum(case when dr1 = 2 then 时间差 when dr2 =2 then -时间差 else 0 end )
select distinct exam_id,duration,release_time
from
(
select exam_id,duration,release_time,
sum(case when dr1 = 2 then stm when dr2 = 2 then -stm else 0 end) as sub
from
(
select er.exam_id,ei.duration,ei.release_time,timestampdiff(minute,start_time,submit_time) as stm,
row_number() over(partition by er.exam_id order by timestampdiff(minute,start_time,submit_time) desc) as dr1,
row_number() over(partition by er.exam_id order by timestampdiff(minute,start_time,submit_time) asc) as dr2
from exam_record er left join examination_info ei on er.exam_id = ei.exam_id
where er.submit_time is not null
) t
group by t.exam_id
) a
where sub >= duration/2
order by exam_id desc