【问题标题】:Redshift Merge rows and conflict-resolve by timestampRedshift 合并行并按时间戳解决冲突
【发布时间】:2019-05-06 19:08:42
【问题描述】:

这与selecting row with latest timestamp question 不同,并且特定于 Redshift

我希望允许用户在不同时间点更新(暂存)表行的部分内容同时避免调用 UPDATE 语句。这是通过仅追加方法完成的,在这种方法中,我们不断添加行,其中只有唯一 id 和时间戳是强制性的,其他列可能提供也可能不提供值。

问题:

给定一个表,其中除了“主键”(未真正强制执行)和时间戳列之外,该表中的所有其他列都是 可为空,我如何合并具有相同主键的所有行如果存在一个这样的非空值,通过为每个可为空的列选择最近的非空值来键入一行。

例子:

|id|timestamp|status|stringcol|numcol|
|1 |456      |begin |         |      |
|1 |460      |      |         |  2   |
|2 |523      |      |  foo    |      |
|1 |599      |mid   |  blah   |      |
|2 |624      |begin |         |      |
|1 |721      |done  |         |  60  |

应该产生

|id|timestamp|status|stringcol|numcol|
|2 |624      |begin |  foo    |      |
|1 |721      |done  |  blah   |  60  |

【问题讨论】:

标签: amazon-redshift


【解决方案1】:

这可以通过结合使用 Redshift 的 LISTAGG 函数和 SPLIT_PART 函数来实现。

使用上面的示例 5 列表,您需要这样的东西:

SELECT id, 
       MAX(last_updated),
       SPLIT_PART(LISTAGG(status, ',') WITHIN GROUP(ORDER BY last_updated DESC), ',', 1),
       SPLIT_PART(LISTAGG(stringcol, ',') WITHIN GROUP(ORDER BY last_updated DESC), ',', 1),
       SPLIT_PART(LISTAGG(numcol, ',') WITHIN GROUP(ORDER BY last_updated DESC), ',', 1)
FROM table
GROUP BY 1;

【讨论】:

  • 以上查询需要last_updated也属于group by
  • 感谢@mdem7,这是一个错字,但实际上是在 last_updated 而不是group by
猜你喜欢
  • 2012-03-01
  • 2015-10-15
  • 2017-05-10
  • 2019-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-29
  • 2021-07-28
相关资源
最近更新 更多