Oracle SQL - Comparing Multiple Rows with Dates -
i'm working in oracle sql. suppose have table lists following.
table
purchaseid custid location date 1 1 8/23/2013 12:00:00 2 1 b 8/15/2013 12:00:00 3 2 5/15/2013 12:00:00 4 2 b 1/01/2005 12:00:00 5 3 1/15/2001 12:00:00 6 3 1/30/2001 12:00:00 7 3 b 8/23/2013 12:00:00 8 4 5/05/2012 12:00:00 9 4 b 8/15/2010 12:00:00 10 4 9/20/2008 12:00:00
i'm trying write query compares purchases customer output every instance particular customer makes purchase @ 2 different locations within 2 years of each other. i'm getting particularly tripped on custid=3 , custid=4 type cases, there difficult combinations of location/date. output of query should this.
purchaseid custid location date 1 1 8/23/2013 12:00:00 2 1 b 8/15/2013 12:00:00 8 4 5/05/2012 12:00:00 9 4 b 8/15/2010 12:00:00 10 4 9/20/2008 12:00:00
in output, custid=1's purchases returned because in different locations within 2 years of each other. custid=2 thrown out because not within 2 years. custid=3 has 2 purchases within 2 years of each other, thrown out because in same location. , custid=4's purchases kept because purchases 8 , 9 within 2 years , in different locations, , 9 , 10 within 2 years , in different locations (i want these kept despite 8 , 10 being in same location , not within 10 years).
note: date column has oracle sql 'date' datatype.
as always, help/guidance appreciated.
you can limit search cases either next or previous location different current one. @ time difference choose rows.
this makes heavy use of lag()
, lead()
:
select t.pruchaseid, t.custid, t.location, t.date (select t.*, lag(location) on (partition custid order date) prevloc, lead(location) on (partition custid order date) nextloc, lag(date) on (partition custid order date) prevdate, lead(date) on (partition custid order date) nextdate t ) t ((prevloc <> location) , (add_months(prevdate, 2*12) > date)) or ((nextloc <> location) , (add_months(date, 2*12) > nextdate));
Comments
Post a Comment