当前位置:   article > 正文

每日刷力扣SQL题(三)

每日刷力扣SQL题(三)

2356.每位教师所教授的科目种类的数量

考察点:聚合函数 、不同系所教课程相同 所以可以用关键字distinct来区分

  1. select teacher_id , count(distinct subject_id )as cnt
  2. from Teacher
  3. group by teacher_id

1141.查询近三十天活跃用户数

考察点:近三十天 包括当天 日期时间段应减去29天 

  1. Select activity_date as day,count(distinct(user_id)) as active_users
  2. from Activity
  3. where activity_date >= '2019-07-27' - INTERVAl 29 DAY and activity_date <= '2019-07-27'
  4. group by activity_date

更准确的解法:

1、使用Between and 关键字 和 判断activity_type是否为NULL

  1. SELECT activity_date as day, count(distinct user_id) as active_users
  2. FROM Activity
  3. WHERE activity_date between date_sub("2019-07-27", interval 29 day) and "2019-07-27" AND (activity_type is not null)
  4. GROUP BY 1;

1084.销售分析|||

两种写法

其实题目要求“仅在2019-01-01至2019-03-31之间出售的商品”翻译过来就是“所有售出日期都在这个时间内”,也就是“在这个时间内售出的商品数量等于总商品数量”,这样就不难写出这个语句

  1. select sales.product_id as product_id, product.product_name as product_name
  2. from sales left join product on sales.product_id = product.product_id
  3. group by product_id
  4. having count(sale_date between '2019-01-01' and '2019-03-31' or null) = count(*)
  1. Select s.product_id as product_id , product_name
  2. from Sales s left join Product p on s.product_id = p.product_id
  3. group by s.product_id
  4. having count(IF(sale_date between '2019-01-01' and '2019-03-31',1,null)) = count(*)

其他解法:

  1. SELECT DISTINCT
  2. p.product_id,
  3. p.product_name
  4. FROM
  5. Product p
  6. JOIN
  7. Sales s ON p.product_id = s.product_id
  8. WHERE
  9. s.sale_date BETWEEN '2019-01-01' AND '2019-03-31'
  10. AND s.product_id NOT IN (
  11. SELECT
  12. s2.product_id
  13. FROM
  14. Sales s2
  15. WHERE
  16. s2.sale_date < '2019-01-01'
  17. OR s2.sale_date > '2019-03-31'
  18. );

596.超过5名学生的课

  1. select class
  2. from Courses
  3. group by class
  4. having Count(student) >= 5

1729.求关注者的数量

  1. select user_id , count(follower_id) as followers_count
  2. from Followers
  3. group by user_id
  4. Order by user_id ASC;

619.只出现一次的最大数字

  1. select Max(num) as num
  2. from
  3. (select num
  4. from MyNumbers
  5. group by num
  6. having count(*) = 1 ) as Number

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/1021276
推荐阅读
相关标签
  

闽ICP备14008679号