跟踪审计表中的更改

时间:2014-04-02 10:58:37

标签: sql sql-server

我有一个审计表如下:

empid|division id|dept id|lastupdated
1|      A|             20|xxxxx
3|      C|             10|xxxxxx
6|      D|             10|xxxxxx
1|      D|             10|xxxxxx
1|      B|             10|xxxxxx
3|      E|             10|xxxxxx

我需要过滤出dept id = 10的记录,该记录已在过去2天内更新 但是,只有当同一个emp的前一个条目具有不同的部门时,才应选择该记录。

即。找出过去2天内更新的所有记录,其中部门已在上次更新中“更改”为10(来自其他地方)。
请注意,对该人的最后更新可能比2天的窗口早得多 所以预期产出高于 -

1|      D|             10|xxxxxx

这可以在不诉诸临时表的情况下完成吗?

4 个答案:

答案 0 :(得分:0)

SELECT t1.*
FROM tableName t1
INNER JOIN tableName t2
ON t1.emp_id=t2.emp_id and t1.dept_id<>t2.dept_id
WHERE datediff(day,t1.lastudated,GETDATE())<=2 AND t1.lastupdated > t2.lastupdated 

SQL Fiddle Demo

答案 1 :(得分:0)

试试这个

select t1.* from tablename as t1 inner join
(
    select emp_id from tablename
    where lastudated>=dateadd(day,-2,lastudated)
    group by emp_id
    having min(dep_id)<>max(dept_id) and min(dept_id)=10
) as t2 on t1.emp_id=t2.emp_id

答案 2 :(得分:0)

试试这个,

select t1.* from tablename as t1 
cross apply(
                select t2.emp_id from tablename as t2
                where DATEDIFF(dd,t2.lastudated,dateadd(day,-2,GETDATE())) = 0
                and t2.emp_id = t1.emp_id
                and t1.dept_id <> t2.dept_id
            ) as t3 

答案 3 :(得分:0)

我觉得这应该会让你到达或靠近你想去的地方。

SELECT t1.empid ,
       t1.divisionid ,
       t1.deptid ,
       t1.lastupdated 
FROM  YourTable t1
INNER JOIN YourTable t2 ON t1.empid=t2.empid and t1.deptid<>t2.deptid and t1.lastupdated>t2.lastupdated
WHERE t1.lastupdated BETWEEN DateAdd(day, -3, GetDate()) AND DateAdd(day, 1, GetDate())
     AND t2.lastupdated BETWEEN DateAdd(day, -3, GetDate()) AND DateAdd(day, 1, GetDate())