当前位置:   article > 正文

每日刷力扣SQL题(六)

每日刷力扣SQL题(六)

1978.上级经理已离职的公司员工

  1. select employee_id
  2. from Employees
  3. where salary < 30000 and manager_id not in (
  4. select distinct employee_id from Employees
  5. )
  6. order by employee_id ASC

626 换座位

 在 SQL 中实现每两行交换数据可以通过使用窗口函数和自连接来完成。

  1. # Write your MySQL query statement below
  2. With RankedValues AS
  3. (
  4. select id ,
  5. student,
  6. ROW_NUMBER() OVER (order by id) AS rn
  7. from Seat
  8. ),
  9. SwappedValues AS
  10. (
  11. select
  12. CASE
  13. when rn%2 = 1 then id + 1
  14. ELSE id -1
  15. END AS new_id ,
  16. student
  17. from RankedValues
  18. )
  19. select
  20. ROW_NUMBER() over(order by new_id) as id,
  21. student
  22. from SwappedValues
  23. order by id ASC

解释

  1. RankedValues CTE: 使用 ROW_NUMBER() 函数为每一行分配一个序号 rn,以便我们可以知道每行的位置。

  2. SwappedValues CTE: 根据行号 rn 的奇偶性,决定新的 ID。奇数行的 ID 加 1,偶数行的 ID 减 1。

  3. 最终选择: 再次使用 ROW_NUMBER() 来生成新 ID,并按新 ID 排序,得到交换后的结果。

    注意事项

  4. 此方法假设表的行数是偶数。如果是奇数,最后一行将保持不变。
  5. 确保在实际使用中对数据的完整性和约束条件进行处理。

其他解法:使用CASE

  1. select (
  2. CASE
  3. WHEN id % 2 = 0 THEN (id - 1)
  4. WHEN id % 2 = 1 AND id < (select MAX(ID) from Seat) THEN id + 1
  5. ELSE id
  6. END
  7. ) id, student from Seat order by id
  1. SELECT
  2. (CASE
  3. WHEN MOD(id, 2) != 0 AND counts != id THEN id + 1
  4. WHEN MOD(id, 2) != 0 AND counts = id THEN id
  5. ELSE id - 1
  6. END) AS id,
  7. student
  8. FROM
  9. seat,
  10. (SELECT
  11. COUNT(*) AS counts
  12. FROM
  13. seat) AS seat_counts
  14. ORDER BY id ASC;

1341.电影评分 

使用UNION ALL 来联合所有查询 并且使用DATE_FORMAT来格式化日期

  1. # Write your MySQL query statement below
  2. (
  3. select u.name as results
  4. from Users u join MovieRating mr on u.user_id = mr.user_id
  5. group by u.user_id
  6. order by count(*) DESC,name ASC
  7. limit 1
  8. )
  9. UNION ALL
  10. (
  11. select m.title as results
  12. from Movies m left join MovieRating mr on m.movie_id = mr.movie_id and DATE_FORMAT(mr.created_at ,'%Y-%m') = '2020-02'
  13. group by mr.movie_id
  14. order by AVG(mr.rating) DESC,title
  15. limit 1
  16. )

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

闽ICP备14008679号