SQL Server Filter items for a user -
i have order table , orderitem table. orders user placed less or equal 2 mins between them , have same products(number of products must match well) associated them.
based on question i'm able sucessfully filter out order placed <=2 mins apart user. i'm unable figure out how able orders user have same products associated them well.
i expecting output like
ordernumber orderdatetime userid 1111 april, 28 2012 09:00:00 1 3333 april, 28 2012 09:03:00 1 4444 april, 28 2012 09:40:00 2 5555 april, 28 2012 09:42:00 2
here have tried far: sql fiddle
using sql fiddle, came this...
with ordered ( select ordernumber, orderdatetime, userid, lag(orderdatetime,1) on ( partition userid order orderdatetime ) prev_time, lead(orderdatetime,1) on ( partition userid order orderdatetime ) next_time, lag(ordernumber,1) on ( partition userid order orderdatetime ) prev_ordernumber, lead(ordernumber,1) on ( partition userid order orderdatetime ) next_ordernumber [order] ), possibleduplicateorders ( select ordernumber, orderdatetime, userid, case when datediff(minute,orderdatetime,next_time) <= 2 next_ordernumber when datediff(minute,prev_time,orderdatetime) <= 2 prev_ordernumber else null end duplicateordernumber ordered datediff(minute,orderdatetime,next_time) <= 2 --this says if next value less or equal 2 minutes away return or datediff(minute,prev_time,orderdatetime) <= 2 --this says if prev value less or equal 2 minutes away return ) select * possibleduplicateorders pdo not exists ( select * order_item oi_left left join order_item oi_right on oi_right.ordernumber = pdo.duplicateordernumber , oi_right.productid = oi_left.productid oi_left.ordernumber = pdo.ordernumber , oi_right.productid null ) , not exists ( select * order_item oi_left left join order_item oi_right on oi_right.ordernumber = pdo.ordernumber , oi_right.productid = oi_left.productid oi_left.ordernumber = pdo.duplicateordernumber , oi_right.productid null )
from can see, orders 4444 , 5555 should considered duplicates criteria. (within 2 minutes of each other , have matching items.) sql fiddle did not include quantities, did not include them in query, can add them in if need them.
Comments
Post a Comment