Click here to Skip to main content
15,885,365 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
Hi,
There is table. I want to fetch distinct record from that based on time difference. Table structure is as follows-

  A       B        C
FLM123  Down    1/8/2014 09:08
FLM124  Down    1/8/2014 11:08
FLM125  Down    1/8/2014 16:08
FLM126  UP      1/8/2014 12:08
FLM127  Bottom  1/8/2014 11:08
FLM128  Level   1/8/2014 10:08
FLM129  Matched 1/8/2014 12:08



Condition=> If Difference between time of two rows defined in column C group by A and B is greater than 4 hrs then eliminate one row from the result.

Result I want-

  A       B        C
FLM123  Down    1/8/2014 09:08
FLM125  Down    1/8/2014 16:08
FLM126  UP      1/8/2014 12:08
FLM127  Bottom  1/8/2014 11:08
FLM128  Level   1/8/2014 10:08
FLM129  Matched 1/8/2014 12:08



How to write a query for this result as I have thousands of record like this.
Please help.
Posted
Updated 27-May-14 5:45am
v2
Comments
joshrduncan2012 27-May-14 10:17am    
Help you with what? You haven't shown us any effort on your part first. What have you tried? Where are you stuck?
Sunasara Imdadhusen 28-May-14 1:38am    
Correct, you should try to that and then ask for help if you really stuck.
Maciej Los 4-Mar-15 15:20pm    
"If Difference between time of two rows defined in column C group by A and B is greater than 4 hrs" - in comparison to what record?

1 solution

Use below query, it will work only Sqlserver 2012 or higher


SQL
SELECT a,b, c, LEAD(c) OVER (ORDER BY a) NextRow,datediff(HOUR,c,isnull(LEAD(c) OVER (ORDER BY a),c)) as TimeDiff
FROM #TestTable


see the link for Lead and Lag function

http://blog.sqlauthority.com/2013/09/22/sql-server-how-to-access-the-previous-row-and-next-row-value-in-select-statement/[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900