LeetCode_sql_day09(1164.指定日期的产品价格)

描述:1164.指定日期的产品价格

编写一个解决方案,找出在 2019-08-16 时全部产品的价格,假设所有产品在修改前的价格都是 10 

输出如下 :

数据准备:

Create table If Not Exists Products (product_id int, new_price int, change_date date)

Truncate table Products

insert into Products (product_id, new_price, change_date) values ('1', '20', '2019-08-14')

insert into Products (product_id, new_price, change_date) values ('2', '50', '2019-08-14')

insert into Products (product_id, new_price, change_date) values ('1', '30', '2019-08-15')

insert into Products (product_id, new_price, change_date) values ('1', '35', '2019-08-16')

insert into Products (product_id, new_price, change_date) values ('2', '65', '2019-08-17')

insert into Products (product_id, new_price, change_date) values ('3', '20', '2019-08-18')

分析:

①先将数据根据product_id排序,同时算出change_date与2019-08-16两日期的差值

select product_id,
                   new_price,
                   change_date,
                   datediff(change_date, '2019-08-16') diff
            from Products
            order by product_id

②根据diff筛选出小于等于0 的(即在2019-08-16及之前的数据),在被筛选后的数据中找出max(change_date)即离2019-08-16最近的。

select *
         from t1
         where diff <= 0
select product_id,
       new_price,
       change_date,
       max(change_date) over(partition by product_id) r2
from t2
select * from t3 where r2 = change_date

③将具有完整product_id的表与该表连接,同时用ifnull(new_price,10)完善数据

select t5.product_id,
       ifnull(new_price,10) price
from(select distinct product_id from products)t5
    left join t4 on t5.product_id = t4.product_id

代码:

with t1 as (select product_id,
                   new_price,
                   change_date,
                   datediff(change_date, '2019-08-16') diff
            from Products
            order by product_id)
, t2 as (select *
         from t1
         where diff <= 0)
,t3 as (
select product_id,
       new_price,
       change_date,
       max(change_date) over(partition by product_id) r2
from t2
)
, t4 as (select * from t3 where r2 = change_date)
select t5.product_id,
       ifnull(new_price,10) price
from(select distinct product_id from products)t5
    left join t4 on t5.product_id = t4.product_id
;

总结:

筛选2019-08-16时的各商品价格较难

此处用的是datediff()函数先找差值,然后取最值筛选找到各商品与需求日期最近的数据

  • 15
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值