【问题标题】:Redshift - Missing latest date when join two tablesRedshift - 加入两个表时缺少最新日期
【发布时间】:2020-01-12 01:13:28
【问题描述】:

我有两个表(分别称为 A 和 B 表);

表格 - 数据仅包含最近 1 个月的数据。 表 - B 数据存储您拥有的所有数据。

|user | table_A_date | amount_table_A|
|-----| ------------ | ------------- |
| A   |2019-11-30    |1111.0         |
| A   |2019-12-02    |1111.0         |
| A   |2019-12-05    |1111.0         |
| A   |2019-12-09    |1111.0         |


|user | table_B_date | amount_table_B|
|-----| ------------ | ------------- |
| A   |2019-11-25    |1111.0         |
| A   |2019-12-02    |1111.0         |
| A   |2019-12-05    |1111.0         |
| A   |2019-12-10    |1111.0         |

我需要找出这两个表日期之间的差异,但是当我离开加入这两个表时,我的日期为空:

|user     | table_A_date |  table_B_date | amount_table_A|
| ------- | -------      | -------       | -----   |
| A       |2019-11-30    |   Null        |1111.0   |
| A       |2019-12-02    |2019-12-02     |1111.0   |
| A       |2019-12-05    |2019-12-05     |1111.0   |
| A       |2019-12-09    |    Null       |1111.0   |

我将使用last_value over () 函数,但我仍然缺少第一个null 值。如何存储每个用户之前的最后一个值(for user A 2019-11-25)

【问题讨论】:

  • 轴,是否在 A 中而不在 B 中和在 B 中而不在 A 中查找行?我有点困惑
  • 嗨@zip,谢谢你的评论。我需要将最新数据(仅日期)存储在表 B 中,但不在表 A 中
  • 通过发布的示例,您可以显示预期的结果吗?我们将能够立即答复

标签: sql amazon-redshift


【解决方案1】:

您可以将full joinlag()/last_value() 一起使用,然后进行过滤:

select ab.*
from (select coalesce(a.user, b.user) as user,
             a.date as a_date, a.amount as a_amount,
             coalesce(b.date,
                      lag(b.date ignore nulls) over (partition by user order by b.date)
                         ) as b_date,
             coalesce(b.amount,
                      lag(b.amount ignore nulls) over (partition by user order by b.date)
                     ) as b_amount
      from a full join
           b
           on a.user = b.user and a.date = b.date
     ) ab
where a_date is not null;

【讨论】:

  • @Axis 。 . .好问题。我实际上不得不考虑这个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-23
  • 2019-05-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多