SQL Server - 查找列中的重复条目

时间:2017-03-14 10:48:41

标签: sql-server sql-server-2008

有人可以帮助我找到以下示例的解决方案吗?

enter image description here

用户(OperatorID)执行的每项工作都应具有IN& OUT,如果对于一个实例,用户在连续的行中输入IN两次或OUT输入两次,那么我需要将最新的事务仅输入到我的结果中。

所以,在上面的例子中,ID(102)是我们感兴趣的,而忽略了其余的。

"位置"可以是任何东西,即SI / SO,D1 / DO等。

1 个答案:

答案 0 :(得分:2)

使用exists()获取id=id-1operatoridlocation相同的副本的第二行:

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
)