Find date sequence in PostgreSQL -
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 postgresql 2014.
thanks
trying:
select custid, max(num_days) longest ( select custid,rn, count (*) num_days ( select custid, date(orderdate), cast (row_number() on (partition custid order date(orderdate)) varchar(5)) rn table_ ) x group custid, current_date - interval rn|| ' day' ) y group custid
try:
select custid, max( abc ) max_sequence_of_days ( select custid, yy, count(*) abc ( select * , sum( xx ) on (partition custid order orderdate ) yy ( select * , case when orderdate - lag( orderdate ) on (partition custid order orderdate ) <= 1 0 else 1 end xx mytable ) x ) z group custid, yy ) q group custid
demo: http://sqlfiddle.com/#!15/00422/11
===== edit ===========
got "operator not exist: interval <= integer"
this means orderdate
column of type timestamp
, not date
.
in case need use <= interval '1' day
condition instead of <= 1
:
please see link: https://www.postgresql.org/docs/9.0/static/functions-datetime.html learn more date arithmetic in postgresql
please see demo: http://sqlfiddle.com/#!15/7c2200/2
select custid, max( abc ) max_sequence_of_days ( select custid, yy, count(*) abc ( select * , sum( xx ) on (partition custid order orderdate ) yy ( select * , case when orderdate - lag( orderdate ) on (partition custid order orderdate ) <= interval '1' day 0 else 1 end xx mytable ) x ) z group custid, yy ) q group custid
Comments
Post a Comment