当前位置:   article > 正文

每日刷力扣SQL题(五)

每日刷力扣SQL题(五)

1164.指定日期的产品价格

        一、方法:使用left join 和 ifnull
       
 思路

        本题的关键点在找到 2019-08-16 前所有有改动的产品及其最新价格和没有没有修改过价格的产品。 我们可以先找到所有的产品,再找到所有 2019-08-16 前有修改的产品和他们最新的价格,使用 left join 将两个查询联合。如果产品没有价格,说明没有修改过,设置为 10,如果有价格,设置为最新的价格

找出所有的产品

找到 2019-08-16 前所有有改动的产品的最新价格。

上面两步已经找到了所有的产品和已经修改过价格的产品。使用 left join 得到所有产品的最新价格,如果没有设置为 10

  1. select p1.product_id , ifNULL(p2.new_price,10) as price
  2. from
  3. (select distinct product_id from Products)
  4. as p1
  5. left join
  6. ( select product_id ,new_price
  7. from Products
  8. where (product_id , change_date) in
  9. (select product_id, max(change_date) as change_date From Products where change_date <='2019-08-16' group by product_id )
  10. group by product_id ) as p2 on p1.product_id = p2.product_id

二、方法:使用UNION关键字 合并多个查询集的结果

  1. -- Subquery 1: Get the latest product_id and change_date on or before '2019-08-16'
  2. SELECT product_id, new_price as price
  3. FROM Products
  4. WHERE (product_id, change_date) in (SELECT product_id, max(change_date) as change_date
  5. FROM Products
  6. WHERE change_date <= '2019-08-16'
  7. GROUP BY product_id)
  8. UNION ALL
  9. -- Subquery 2: Get product_id where the earliest change_date is after '2019-08-16' with a fixed price of 10
  10. SELECT product_id, 10 as price
  11. FROM Products
  12. GROUP BY product_id
  13. HAVING MIN(change_date)> '2019-08-16';

1204.最后一个能进巴士的人

 思路:按照turn排序的,按照weight进行累加,按照累加的大小进行倒序排序,通过limit 1 选取最后一位上车的人

  1. # Write your MySQL query statement below
  2. select person_name
  3. from
  4. (select person_name,
  5. sum(weight) over(order by turn) as current_weight
  6. from Queue) as a
  7. where current_weight <=1000
  8. order by current_weight desc
  9. limit 1

1907.按分类统计薪水

使用UNION关键字联合查询

  1. -- select category,count(*) as accounts_count
  2. -- from
  3. -- (select * ,
  4. -- CASE
  5. -- WHEN income < 20000 then 'Low Salary'
  6. -- WHEN income >= 20000 and income <= 50000 then 'Average Salary'
  7. -- WHEN income > 50000 then 'High Salary'
  8. -- END as category
  9. -- from Accounts ) as a
  10. -- group by category
  11. select 'Low Salary' as category , count(*) as accounts_count from Accounts
  12. where income < 20000
  13. union
  14. select 'Average Salary' as category , count(*) as accounts_count from Accounts
  15. where income >= 20000 and income <= 50000
  16. union
  17. select 'High Salary' as category , count(*) as accounts_count from Accounts
  18. where income > 50000

其中联合查询语句 可以用CASEWHEN来实现

以下为‘Low Salary’为例子

  1. SELECT
  2. 'Low Salary' AS category,
  3. SUM(CASE WHEN income < 20000 THEN 1 ELSE 0 END) AS accounts_count
  4. FROM
  5. Accounts

 

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

闽ICP备14008679号