SQL牛客网刷题易错点2

牛客网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’)

4,例题SQL127
SQL牛客网刷题易错点2_第1张图片
SQL牛客网刷题易错点2_第2张图片

  • 出现only_full_group_by报错时,可以通过在没有在group by中存在且是非聚合列上加any_value()就可以了
  • 计算某年某月含有的天数:day(last_day(所给的时间字段))
  • 可直接 ‘2021汇总’ 做字段中的值
  • 在union 中,order by 只放在最后,即union后再order by
  • 报错记得检查英文逗号,括号对应

5,统计某列中不为空的值个数:count(列名)
统计某列中为空的个数:if(列名 is null, 1, null)

6,例题SQL128
SQL牛客网刷题易错点2_第3张图片
SQL牛客网刷题易错点2_第4张图片

  • 题目中如果有时间要求,要记得限制

内容组合:

  • 对于每条作答,用:连接日期和tag:concat_ws(‘:’, date(start_time), tag)
    date(start_time) 是将字段start_time中值从2021-09-01 12:31:01截取到2021-09-01
  • 对于一个用户(组内)的多条作答,用;连接去重后的作答记录:group_concat(distinct concat_ws(‘:’, date(start_time), tag) separator ‘;’)
  • 如果有排序需求,记得写

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
SQL牛客网刷题易错点2_第5张图片
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

你可能感兴趣的:(数据库SQL刷题,sql,java,数据库)