【问题标题】:Select only changes to a value from an audit log table仅选择对审计日志表中值的更改
【发布时间】:2013-01-24 14:56:13
【问题描述】:

在 MS SQL Server 2008 R2 中,我有一个表 Foo,对于 Foo 上的每次插入和更新,我还将日期、用户、PK FooId 和 Foo 的其他一些列插入到 FooAuditLog 中,包括一个数值,称之为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,但我确实需要捕获值变回先前值的条目。

【问题讨论】:

  • 你用的是什么关系型数据库?
  • 你忽略11/7, 11/9, and 11/14的逻辑是什么?
  • @Kaf:我只想选择所需值 (cxp) 已更改的日志条目。在提到的日期,cxp 与上次保存时相同。

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


【解决方案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

【讨论】:

    猜你喜欢
    • 2018-12-24
    • 2019-06-26
    • 2015-11-26
    • 2010-11-20
    • 2023-03-28
    • 2018-04-26
    • 2018-01-25
    • 2011-06-29
    • 2012-08-31
    相关资源
    最近更新 更多