Sql-Server

確定訂單連續性

  • January 23, 2020

對於特定客戶,我有一個查詢返回的數據,如下所示:

OrderDate   OrderCount
2020-01-12  0
2020-01-13  17
2020-01-14  22
2020-01-15  21
2020-01-16  30
2020-01-17  12
2020-01-18  0
2020-01-20  0
2020-01-21  49
2020-01-22  28
2020-01-23  4

這些是該客戶每個工作日的訂單數量。我如何有效地確定他們目前的“連續”訂單?例如,如果今天是 2020 年 1 月 24 日,答案將是 3,因為他們已經訂購了 3 天,沒有錯過任何一天。

請注意,這些天可能並不總是連續的。查詢未返回一些非工作日(例如,2020-01-19)。

誰能告訴我該怎麼做?提前致謝!

正如mustaccio 指出的那樣,這是一個“差距和島嶼”問題:

declare @date date = '2020-01-16';


with ct as
(
   /* First you must detect the gaps, filtering those rows lesser than the selected date */
   select
       OrderDate,
       case when 
           datediff(day, 
                    coalesce(lag(OrderDate) over (order by OrderDate), OrderDate),
                    OrderDate
                    ) <> 1 then 1 else 0 end rst
   from
       orders
   where
       OrderDate <= @date
)
, ct2 as
 (
     /* Then set an island of each group */
     select
         OrderDate,
         sum(rst) over (order by OrderDate) as grp
     from 
         ct
  )
  /* And finally count the affected rows */
  select top 1
      count(OrderDate) streak
  from
      ct2
  group by
      grp
  order by
      max(OrderDate) desc;
| 連勝 |
| -----: |
| 5 |

db<>在這裡擺弄

引用自:https://dba.stackexchange.com/questions/258094