将来自时间表的原始数据与当前数据一起包含在视图中吗?

huangapple go评论58阅读模式
英文:

Include original data with current data from temporal tables in a view?

问题

你想要如何处理这个问题?

英文:

I am creating a view based on a system-versioned table that records account information. The primary key is an automatically-incremented "Account No". My period columns are "Valid From" and "Valid To". I also assign a new "Version No" each time the data changes.

Within this view, I would like to use the "Valid From" value from the most recent version of each account to represent the account's "Time Modified." Then, I would like to use the "Valid From" value from the oldest version of each account (i.e., where "Version No" = 1) to represent the account's "Time Created."

How should I do this?

答案1

得分: 1

以下是翻译好的内容:

虽然可以使用 FOR SYSTEM_TIME ALL 和聚合,但直接连接历史表可能是最简单(也是最快)的方法。

SELECT
  a.*,
  ISNULL(ah.ValidFrom, a.ValidFrom) AS TimeCreated
FROM Account a
LEFT JOIN (
    SELECT ah.*,
      rn = ROW_NUMBER() OVER (PARTITION BY ah.AccountNo ORDER BY ah.ValidFrom)
    FROM Account_History ah
) ah ON ah.AccountNo = a.AccountNo AND ah.rn = 1;

你也可以将其作为 APPLY 或标量子查询来执行。这可能会根据涉及的基数而有所不同。你应该尝试这两种选项。

SELECT
  a.*,
  ISNULL(ah.ValidFrom, a.ValidFrom) AS TimeCreated
FROM Account a
OUTER APPLY (
    SELECT TOP (1) ah.*
    FROM Account_History ah
    WHERE ah.AccountNo = a.AccountNo
    ORDER BY ah.ValidFrom
) ah;
英文:

While it is possible to use FOR SYSTEM_TIME ALL and aggregation, it's probably easiest (and fastest) to just join the history table directly.

SELECT
  a.*,
  ISNULL(ah.ValidFrom, a.ValidFrom) AS TimeCreated
FROM Account a
LEFT JOIN (
    SELECT ah.*,
      rn = ROW_NUMBER() OVER (PARTITION BY ah.AccountNo ORDER BY ah.ValidFrom)
    FROM Account_History ah
) ah ON ah.AccountNo = a.AccountNo AND ah.rn = 1;

You can also do this as an APPLY or scalar subquery. This may or may not be faster depending on the cardinalities involved. You should try both options.

SELECT
  a.*,
  ISNULL(ah.ValidFrom, a.ValidFrom) AS TimeCreated
FROM Account a
OUTER APPLY (
    SELECT TOP (1) ah.*
    FROM Account_History ah
    WHERE ah.AccountNo = a.AccountNo
    ORDER BY ah.ValidFrom
) ah;

huangapple
  • 本文由 发表于 2023年6月6日 04:19:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76409746.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定