SQL to determine minimum sequential days of access?

前端 未结 19 1701
我在风中等你
我在风中等你 2020-12-04 04:58

The following User History table contains one record for every day a given user has accessed a website (in a 24 hour UTC period). It has many thousands of r

19条回答
  •  失恋的感觉
    2020-12-04 05:26

    How about one using Tally tables? It follows a more algorithmic approach, and execution plan is a breeze. Populate the tallyTable with numbers from 1 to 'MaxDaysBehind' that you want to scan the table (ie. 90 will look for 3 months behind,etc).

    declare @ContinousDays int
    set @ContinousDays = 30  -- select those that have 30 consecutive days
    
    create table #tallyTable (Tally int)
    insert into #tallyTable values (1)
    ...
    insert into #tallyTable values (90) -- insert numbers for as many days behind as you want to scan
    
    select [UserId],count(*),t.Tally from HistoryTable 
    join #tallyTable as t on t.Tally>0
    where [CreationDate]> getdate()-@ContinousDays-t.Tally and 
          [CreationDate]=@ContinousDays
    
    delete #tallyTable
    

提交回复
热议问题