【问题标题】:Joining a transaction fact table to a periodic snapshot table in SQL using the nearest date使用最近日期将事务事实表连接到 SQL 中的定期快照表
【发布时间】:2022-12-10 09:50:46
【问题描述】:

我在 AWS 上使用 Redshift,我有两个表,第一个是这样的事务列表:

cust_ID order_date product
100 2022/05/01 A
101 2022/05/01 A
100 2022/05/05 B
101 2022/05/07 B

第二个是快照表,其中包含每个客户在特定时间点的客户属性。虽然第二个表有大多数日期的行,但它没有每个日期的每个客户的行。

cust_ID as_of_date favourite_colour
100 2022/05/01 blue
100 2022/05/02 red
100 2022/05/05 green
100 2022/05/07 red
101 2022/05/01 blue
101 2022/05/04 red
101 2022/05/05 green
101 2022/05/08 yellow

我如何加入表,以便交易表在订单本身的日期具有客户属性,或者如果表 2 中没有交易日期,则在交易前最近的可用日期?

所需输出的示例是:

cust_ID order_date product Favourite_colour as_of_date
100 2022/05/01 A blue 2022/05/01
101 2022/05/01 A blue 2022/05/01
100 2022/05/05 B green 2022/05/05
101 2022/05/07 B green 2022/05/05

由于 order_date/id 组合不在第二个表中的边缘情况,通过 cust_ID 和 order_date = as_of_date 加入不起作用。

我也试过类似的东西:

with snapshot as (
SELECT 
  row_number() OVER(PARTITION BY cust_ID ORDER BY as_of_date DESC) as row_number,
  cust_ID,
  favourite_color,
  as_of_date

FROM table2 t2

INNER JOIN table1 t1
 ON t1.cust_ID = t2.cust_ID
 AND t2.as_of_date <= t1.order_date

)
SELECT * FROM snapshot
WHERE row_number = 1

但是,这不处理同一客户在表 1 中有多个事务的情况。当我检查结果表的计数时,不同 cust_ID 的数量与 count(*) 相同,因此结果表似乎是每个客户只保留一笔交易。

任何帮助,将不胜感激。

【问题讨论】:

    标签: sql amazon-redshift


    【解决方案1】:

    使用您提供的表格输入,我在 DB Fiddle 中测试了这个解决方案,它适用于您想要的输出。

    
        with my_cte AS (
        select *,
               row_number() OVER(PARTITION BY cust_id, order_date ORDER BY as_of_date desc) ranked
          from transactions
     left join attribs using (cust_id)
         where as_of_date <= order_date
     )
     
     select cust_id, order_date, product, favorite_color, as_of_date
      from my_cte
      where ranked  = 1
    order by order_date, cust_id;
    

    【讨论】:

    • 这种方法适用于中小型数据集。但是,对于非常大的数据,循环连接可能会爆炸,并且由于 OP 使用的是 Redshift,因此这是一种可能性。如果是这种情况,UNION ALL 方法会产生更快的结果——我在这里写了一个类似的解决方案stackoverflow.com/questions/65097833/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    • 2017-02-14
    • 2021-02-23
    • 1970-01-01
    • 2014-10-30
    • 1970-01-01
    • 2017-09-26
    相关资源
    最近更新 更多