【问题标题】:Redshift: fetching data from sales table based on date bands from another tableRedshift:根据另一个表中的日期范围从销售表中获取数据
【发布时间】:2023-04-06 14:29:01
【问题描述】:

我的表 t1 包含项目和提前期(供应商交付项目的时间)。 我的表 t2 包含过去 60 天内商品的按日期销售。 我需要在 T1 中添加一个列,其中包含过去提前期天数中 T2 的总销售额。换句话说,我想计算每个项目的提前期不同的提前期销售额。我的表在 Redshift 中。

T1

|---------------------|------------------|
|      item_no        |     Lead Time    |
|---------------------|------------------|
|    10002341         |         7        |
|---------------------|------------------|
|    10002342         |         5        |
|---------------------|------------------|

T2

|---------------------|------------------|
|      item_no        |   Date of sale   | Amount of Sale
|---------------------|------------------|
|    10002341         |   11-06-2020     |   $100
|---------------------|------------------|
|    10002341         |    12-06-2020    |   $200
|---------------------|------------------|

【问题讨论】:

  • 请指定非平凡的样本输入数据和相应的预期输出。也更喜欢使用 CTE(with 子句)而不是纯文本表来指定您的输入数据。或者准备 dbfiddle。它有助于专注于答案而不是文本格式。
  • 谢谢。我搜索了如何将表格放入stackoverflow并得到了这个。 meta.stackoverflow.com/questions/302471/… 将学习 dbfiddle 并更新我的问题。

标签: sql date join sum amazon-redshift


【解决方案1】:

一个选项使用横向连接:

select t1.*, x.*
from t1
left join lateral (
    select coalesce(sum(amount), 0) lead_amount
    from t2
    where 
        t2.item_no = t1.item_no 
        and t2.date_of_sale >= current_date - t1.lead_time * interval '1 day'
) x on true

如果您的数据库不支持横向连接,那么另一种选择是相关子查询:

select 
    t1.*, 
    (
        select coalesce(sum(amount), 0) 
        from t2
        where 
            t2.item_no = t1.item_no 
            and t2.date_of_sale >= current_date - t1.lead_time * interval '1 day'
    ) lead_amount
from t1

【讨论】:

  • 感谢专线小巴。 Redshift 似乎还不支持横向连接。我已经更新了我的标签。
  • 相关子查询有效!虽然它很慢,但至少我有我的答案:)
猜你喜欢
  • 2020-01-07
  • 1970-01-01
  • 1970-01-01
  • 2021-03-26
  • 2022-06-23
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
相关资源
最近更新 更多