我试图在我的数据中找到客户的最大天数。我想了解特定客户制作的最大天数。如果有人在25/8/16 AND 26/08/16和27/08/16以及01/09/16和02/09/16进入我的应用程序 - 最大顺序为3天(25,26, 27)。
最后(输出)我想得到两个字段:custid | MaxDaySequence
我的数据表中有以下字段:custid |订购日期(timestemp)
例如:
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
我正在使用PostgreSQL 2014。
由于
尝试:
select custid, max(num_days) as longest
from (
select custid,rn, count (*) as num_days
from (
select custid, date(orderdate),
cast (row_number() over (partition by custid order by date(orderdate)) as varchar(5)) as rn
from table_
) x group by custid, CURRENT_DATE - INTERVAL rn|| ' day'
) y group by custid
答案 0 :(得分:1)
尝试:
SELECT custid, max( abc ) as max_sequence_of_days
FROM (
SELECT custid, yy, count(*) abc
FROM (
SELECT * ,
SUM( xx ) OVER (partition by custid order by orderdate ) yy
FROM (
select * ,
CASE WHEN
orderdate - lag( orderdate ) over (partition by custid order by orderdate )
<= 1
THEN 0 ELSE 1 END xx
from mytable
) x
) z
GROUP BY custid, yy
) q
GROUP BY custid
演示:http://sqlfiddle.com/#!15/00422/11
=====编辑===========
得到“运算符不存在:interval&lt; = integer”
这意味着orderdate
列的类型为timestamp
,而不是date
在这种情况下,您需要使用<= interval '1' day
条件而不是<= 1
:
请参阅此链接:https://www.postgresql.org/docs/9.0/static/functions-datetime.html以了解有关PostgreSQL中日期算术的更多信息
请看这个演示:
http://sqlfiddle.com/#!15/7c2200/2
SELECT custid, max( abc ) as max_sequence_of_days
FROM (
SELECT custid, yy, count(*) abc
FROM (
SELECT * ,
SUM( xx ) OVER (partition by custid order by orderdate ) yy
FROM (
select * ,
CASE WHEN
orderdate - lag( orderdate ) over (partition by custid order by orderdate )
<= interval '1' day
THEN 0 ELSE 1 END xx
from mytable
) x
) z
GROUP BY custid, yy
) q
GROUP BY custid