【问题标题】:How can I make a left join and bring only the first row that follows a certain condition?如何进行左连接并仅带来符合特定条件的第一行?
【发布时间】:2021-03-12 14:04:18
【问题描述】:

例如,我有这个包含产品价格和价格更新日期的数据集:

category      price       update_date
A             100         2020-01-01
A             120         2020-05-10
A             140         2020-05-15
B             150         2020-01-01
B             200         2020-03-01

这个数据集包含销售额和制作日期:

sale_id     category      sales_date  
1           A             2020-02-01
2           A             2020-03-01    
3           B             2020-02-04 
4           B             2020-03-09 

我想知道每次销售所采用的价格。所以我需要在第二个数据集中获取最后的价格更新和输入。所以我必须带上第一个高于 sales_date 的 update_date。结果我会得到以下数据集:

sale_id     category      sales_date     price
1           A             2020-02-01     100
2           A             2020-05-12     120    
3           B             2020-02-04     150
4           B             2020-03-09     200

有什么想法吗?我想我必须做这样的事情Finding the lowest value in a table greater than a certain value,但我仍然不确定如何适应它。

【问题讨论】:

    标签: sql join left-join amazon-redshift


    【解决方案1】:

    我认为您可以通过为每次更新添加结束日期然后使用 join 来处理此问题:

    select s.*, u.price
    from sales s left join
         (select u.*,
                 lead(update) over (partition by category order by update_date) as next_update_date
          from updates u
         ) u
         on s.category = u.category and
            s.sales_date >= u.update_date and
            (s.sales_date < u.next_update_date or u.next_udpate_date is null)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-23
      • 1970-01-01
      • 2012-06-23
      • 1970-01-01
      相关资源
      最近更新 更多