Find date sequence in SQL Server -
i'm trying find maximum sequence of days customer in data. want understand max sequence of days specific customer made. if enter app in 25/8/16 , 26/08/16 , 27/08/16 , 01/09/16 , 02/09/16 - max sequence 3 days (25,26,27).
in end (the output) want 2 fields: custid | maxdaysequence
i have following fields in data table: custid | orderdate(timestemp)
for exmple: custid orderdate 1 25/08/2007 1 03/10/2007 1 13/10/2007 1 15/01/2008 1 16/03/2008 1 09/04/2008 2 18/09/2006 2 08/08/2007 2 28/11/2007 2 04/03/2008 3 27/11/2006 3 15/04/2007 3 13/05/2007 3 19/06/2007 3 22/09/2007 3 25/09/2007 3 28/01/2008
i'm using sql server 2014.
thanks
there trick, if have incrementing number ordered date subtracting number of days dates same if consecutive. this:
select custid, min(orderdate) start_of_group, max(orderdate) end_of_group, count(*) num_days ( select custid, orderdate row_number() on (partition custid order orderdate) rn ) x group custid, dateadd(day, - rn, orderdate); you take result of , pull out max number of days solve problem:
select custid, max(num_days) longest ( select custid, count(*) num_days ( select custid, orderdate row_number() on (partition custid order orderdate) rn ) x group custid, dateadd(day, - rn, orderdate) ) y group custid
Comments
Post a Comment