2016-11-13 43 views
1

我試圖在我的數據中找到客戶的最大天數序列。我想了解特定客戶所做的最長時間。如果有人在25/8/16和26/08/16和27/08/16和01/09/16和02/09/16輸入我的應用程序 - 最大順序爲3天(25,26, 27)。在PostgreSQL中查找日期順序

最後(輸出)我想得到兩個字段:custid | MaxDaySequence

我在我的數據表中有以下字段:custid |訂購日期(timestemp)

對於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 

我使用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

嘗試: 從( select custid,rn,count(*)as num_daysselect custid,max(num_days)as longest 從(選擇custid,date(orderdate),cast(row_number()over(由custid order by date(orderdate)作爲varchar(5)分區)作爲來自table_的rn)x group by custid,CURRENT_DATE - INTERVAL RN || 'day')y group by custid – RotemY

+0

沒有「Postgres 2014」這樣的東西。目前的版本是9.6。 'select version()'顯示了什麼? –

+0

x86_64-unknown-linux-gnu上的PostgreSQL 9.4.5,由gcc(GCC)編譯4.8.2 20140120(Red Hat 4.8.2-16),64位 – RotemY

回答

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


=====編輯===========


得到了「操作符不存在:區間< =整數「

這意味着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 
+0

謝謝! 得到「運營商不存在:間隔<=整數」 試圖做間隔投入爲整數,但得到'1'作爲最大每個custid – RotemY

+0

我已經更新了答案。此錯誤意味着'orderdate'列是時間戳,而不是日期。 – krokodilko

+0

非常感謝。作品完美 – RotemY