有人可以帮助我找到以下示例的解决方案吗?
用户(OperatorID)执行的每项工作都应具有IN& OUT,如果对于一个实例,用户在连续的行中输入IN两次或OUT输入两次,那么我需要将最新的事务仅输入到我的结果中。
所以,在上面的例子中,ID(102)是我们感兴趣的,而忽略了其余的。
"位置"可以是任何东西,即SI / SO,D1 / DO等。
答案 0 :(得分:2)
使用exists()
获取id=id-1
和operatorid
与location
相同的副本的第二行:
select *
from t
where exists (
select 1
from t i
where i.OperatorId = t.OperatorId
and i.id = t.id-1
and i.Location = t.Location
)
返回:
+-----+---------------------+----------+------+--------+------------+-------------+-------------------+
| id | datetime | location | site | client | operatorId | containerId | WorkflowId |
+-----+---------------------+----------+------+--------+------------+-------------+-------------------+
| 102 | 2017-02-03 11:10:21 | PO | AA | TEMP | Test1 | 451 | 123F-258G-369147C |
+-----+---------------------+----------+------+--------+------------+-------------+-------------------+
<小时/> 如果
Id
不是连续的,您可以使用common table expression row_number()
:
with t as (
select *
, rn = row_number() over (order by id)
from #temp
)
select *
from t
where exists (
select 1
from t i
where i.OperatorId = t.OperatorId
and i.rn = t.rn-1
and i.Location = t.Location
)