0

我试图在我的数据中找到客户的最大天数。我想了解特定客户的最长天数是多少。如果有人在 25/8/16 AND 26/08/16 AND 27/08/16 AND 01/09/16 AND 02/09/16 进入我的应用程序 - 最长序列将是 3 天(25,26, 27)。

最后(输出)我想得到两个字段: custid | 最大日序列

我的数据表中有以下字段: custid | 订单日期(时间)

例如: 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

我正在使用 SQL Server 2014。

谢谢

4

2 回答 2

2

有一个技巧,如果您有一个按日期排序的递增数字,那么如果它们是连续的,那么从您的日期中减去该天数将是相同的。所以像这样:

SELECT custid, 
       min(orderdate) as start_of_group,
       max(orderdate) as end_of_group,
       count(*) as num_days
FROM (
   SELECT custid, orderdate
          ROW_NUMBER() OVER (PARTITION  BY custid ORDER BY orderdate) as rn
) x
GROUP BY custid, dateadd(day, - rn, orderdate);

您可以获取此结果并提取最大天数来解决您的问题:

SELECT custid, max(num_days) as longest
FROM (
  SELECT custid, 
         count(*) as num_days
  FROM (
     SELECT custid, orderdate
            ROW_NUMBER() OVER (PARTITION  BY custid ORDER BY orderdate) as rn
  ) x
  GROUP BY custid, dateadd(day, - rn, orderdate)
) y
GROUP BY custid
于 2016-11-10T21:47:00.743 回答
0

如果你想用 MySQL 解决它:

select user_id,max(num_days) as longest
from(
select user_id, count(*) as num_days
from
(
SELECT    (CASE a1.user_id 
           WHEN @curType 
           THEN @curRow := @curRow + 1 
           ELSE @curRow := 1 AND @curType := a1.user_id END
          ) AS rank,
          a1.user_id,
          a1.last_update as dat
FROM      (select a2.user_id,left(FROM_UNIXTIME(a2.last_update),10) as 'last_update' 
                from visits as a2 group by 1,2) as a1 ,
            (SELECT @curRow := 0, @curType := '') r

ORDER BY  a1.user_id DESC, dat) x
group by user_id, DATE_ADD(dat,INTERVAL -rank day)
) y
group by 1
order by longest desc
于 2017-03-26T19:45:24.983 回答