Sql 跟踪审核表中的更改

Sql 跟踪审核表中的更改,sql,sql-server,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 我需要筛选

我的审计表如下:

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
我需要筛选出部门id=10的记录,这些记录在过去2天内已更新。 但是,仅当同一emp的上一条目具有不同部门时,才应选择该记录

i、 e.查找过去2天内更新的所有记录,其中部门已从上次更新中的内容“更改”为10。 请注意,对此人的最后一次更新可能比2天的时间窗口早得多。 因此,预期产出高于-

1|      D|             10|xxxxxx
不借助临时表就可以做到这一点吗

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 
试试这个

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
试试这个

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 

我想这应该能让你到达或接近你想要到达的地方

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())

这将继续选择记录,如果有任何变化,在其部门在历史上的任何时候。我需要记录被选中只有一次-只有在变化的部门,而不是此后。