仅从审核日志表中选择对值的更改

时间:2013-02-08 18:54:39

标签: sql sql-server-2008 audit-tables

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

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

例如,如果特定Foo(即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,但我需要捕获值更改回先前值的条目。

1 个答案:

答案 0 :(得分: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可能会替换为top甚至fetch first 1 row