英文:
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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论