0

Please could someone help me in finding a solution for the below example?

enter image description here

every work carried out by a user (OperatorID) should have IN & OUT, if for an instance the user enter either IN twice or OUT twice in a consecutive rows then I need to take the latest transaction ONLY onto my results.

So, in my above example ID (102) is what we are interesting in and ignoring the rest.

"Location" can be any thing i.e. SI/SO, D1/DO and so on.

2
  • see the link referenced to know more on how to ask a perfect question:spaghettidba.com/2015/04/24/… Commented Mar 14, 2017 at 10:50
  • also please avoid posting images,unless necessary Commented Mar 14, 2017 at 10:50

1 Answer 1

2

using exists() to get the second row of the duplicate where id=id-1 and operatorid and location are the same:

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 ) 

returns:

+-----+---------------------+----------+------+--------+------------+-------------+-------------------+ | id | datetime | location | site | client | operatorId | containerId | WorkflowId | +-----+---------------------+----------+------+--------+------------+-------------+-------------------+ | 102 | 2017-02-03 11:10:21 | PO | AA | TEMP | Test1 | 451 | 123F-258G-369147C | +-----+---------------------+----------+------+--------+------------+-------------+-------------------+ 


If Id is not sequential, you could use a common table expression with 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 ) 
Sign up to request clarification or add additional context in comments.

8 Comments

Sorry SqlZim, for some reason i ma getting blank results, any idea? I first store the required values in a Temp table, and used your query in the below format. Not sure where I am doing it wrong. could you assist? select t.* from #temp1 t where exists ( select 1 from #temp1 i where i.OperatorId = t.OperatorId and i.id = t.id-1 and i.Location = t.Location )
@satya is Id sequential as it is in your example?
Found what the issue is on my table itself. the ID wasn't (-1) entry. I believe I can now replicate the same principle and work it out. Thanks for Help though
is their a quickest way tp sort if the ID is not sequential? please advise
@satya Updated my answer
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.