将历史表转换为使用范围日期(从和到日期)而不是快照日期

Convert historical tables to use range date (from and to date) instead of snapshot date

我希望这在一个简单的 SQL select 语句中完成,没有任何该环境独有的函数(派生查询、常见 table 表达式、临时 tables INSERT, UPDATE 语句没问题)。检查 post 末尾的我的标签以了解原因。

如有任何问题,请参考我。我在 Whosebug 中找不到与我一样清晰的标题。

用例示例 原文Table:history_table_snapshot

Value|Date
50   |01
50   |02
24   |03
50   |04

已转换 Table:history_table_range

Value|DateStart|DateEnd
50   |01       |03
24   |03       |04
50   |04       |infinity

此外,使此查询处理其他 complicated/high 规模用例(即历史 table 中的 50 列,除主键外的某些列可能为空)

lag window function 应该可以解决问题:

CREATE TABLE history_table_range
(Value, DateStart, DateEnd)
AS 
SELECT Value, Date, LAG (DATE) OVER (ORDER BY date DESC)

编辑:
正如 Gordon Linoff 在评论中指出的那样,仅使用 lead 会更干净:

CREATE TABLE history_table_range
(Value, DateStart, DateEnd)
AS 
SELECT Value, Date, LEAD (DATE) OVER (ORDER BY date)