0

在 MS SQL Server 2008 R2 中,我有一个表 Foo,对于 Foo 的每次插入和更新,我还将日期、用户、PK FooId 和 Foo 的其他一些列插入到 FooAuditLog 中,包括一个数值,叫它cxp。

我现在需要检索给定 FooId 随时间变化的 cxp 更改历史记录。但是可以在不更改 cxp 的情况下保存 Foo,我需要忽略这些值。

例如,如果特定 Foo (ie select date, user, cxp from FooAuditLog where fooId=17) 的审核日志条目如下所示:

Date      User     Cxp
-------------------------
10/26     Fred     42
10/28     George   38
11/7      Tom      38
11/9      Fred     38
11/12     Joe      33
11/14     Tom      33
11/18     George   38

然后我需要修改查询以仅返回:

Date      User     Cxp
-----------------------------
10/26     Fred     42
10/28     George   38
11/12     Joe      33
11/18     George   38

并忽略 11/7、11/9 和 11/14 的条目。我曾考虑过select distinct (cpx) ... group by date,但我确实需要捕获值变回先前值的条目。

4

1 回答 1

1

您需要获取先前的值。此版本使用 MySQL 语法和相关子查询来获取结果:

select t.*
from (select t.*,
             (select cxp from t t2 where t2.date < t.date order by date desc limit1
             ) as prevcxp
      from t
     ) t
where prevcxp is NULL or prevcxp <> cxp

在其他数据库中,您可能会使用lag()而不是子查询,limit可能会被替换为 atop甚至fetch first 1 row.

于 2013-02-08T18:59:33.703 回答