所以 - !我要去從我最後一個問題的查詢開始,其中列出了連續幾天的每次運行。然後,我將按用戶ID和NumConsecutiveDays將其分組,以計算這些用戶有多少天的運行時間。
with numberedrows as
(
select row_number() over (partition by UserID order by CreationDate) - cast(CreationDate-0.5 as int) as TheOffset, CreationDate, UserID
from tablename
)
,
runsOfDay as
(
select min(CreationDate), max(CreationDate), count(*) as NumConsecutiveDays, UserID
from numberedrows
group by UserID, TheOffset
)
select UserID, NumConsecutiveDays, count(*) as NumOfRuns
from runsOfDays
group by UserID, NumConsecutiveDays
;
和當然,如果你想這個過濾器只考慮一定長度的運行,然後把「裏NumConsecutiveDays> = @days」在過去的查詢。
現在,如果您想要將連續16天計爲三次爲期5天的運行,那麼每次運行都會計爲NumConsecutiveDays/@runlength(這將對每個整數進行舍入)。因此,現在不是隻計算每個數的數量,而是使用SUM。你可以使用上面的查詢並使用SUM(NumOfRuns * NumConsecutiveDays/@runlength),但是如果你理解了邏輯,那麼下面的查詢就容易一些。
with numberedrows as
(
select row_number() over (partition by UserID order by CreationDate) - cast(CreationDate-0.5 as int) as TheOffset, CreationDate, UserID
from tablename
)
,
runsOfDay as
(
select min(CreationDate), max(CreationDate), count(*) as NumConsecutiveDays, UserID
from numberedrows
group by UserID, TheOffset
)
select UserID, sum(NumConsecutiveDays/@runlength) as NumOfRuns
from runsOfDays
where NumConsecutiveDays >= @runlength
group by UserID
;
希望這有助於
羅布
你能在你的 「不同的(N) - 天週期」 的確定指標詳細點嗎?如果有人連續2天,那麼差距,然後連續4天,然後一個差距,然後連續8天,是2「不同的4天期」或3? (8天期間連續兩天是4天?) – MatBailie 2009-07-24 14:09:53