2012-09-13 99 views
0

我有表格,我必須更新該特定日期的用戶數量以及過去7天內從指定日期起的用戶數量。樣本數據看起來像計算給定日期過去7天內的用戶數

Date UserCountToday UserCount7days 
20120911 907575 
20120910 953629 
20120909 1366180 
20120908 1388916 
20120907 1009425 
20120906 918638 
20120905 956770 
20120904 1018152 
20120903 1306341 
+0

抱歉,我不udnerstand你的問題 –

回答

0

嘗試:

with cte as 
     (select *,ROW_NUMBER() over(order by [Date]) as row_num 
     from t_users) 
select [Date],UserCountToday, (select SUM(UserCountToday) 
from cte c1 where c.row_num>=c1.row_num 
and abs(c.row_num-c1.row_num)<7) as UserCount7days 
from cte c 

結果

Date UserCountToday UserCount7days 
20120903 1306341 1306341 
20120904 1018152 2324493 
20120905 956770 3281263 
20120906 918638 4199901 
20120907 1009425 5209326 
20120908 1388916 6598242 
20120909 1366180 7964422 
20120910 953629 7611710 
20120911 907575 7501133 
+0

感謝喬!這是很好的幫助:) – user1664644

+0

我們有更快的方法來處理這個問題嗎?我有大量的數據。日期範圍從今天到過去18個月。 – user1664644

+0

@ user1664644:我不這麼認爲..也許這是最快的方法.. –

0
;WITH CTE as (select row_number() over (order by date) as rn,Date,UserCountToday,UserCount7days from tbl5) 

,CTERec as (
select rn,Date,UserCountToday ,UserCountToday as UserCount7days from CTE where rn=1 
union all 
select c.rn,c.Date,c.UserCountToday ,c.UserCountToday+c1.UserCount7days as UserCount7days from CTERec c1 inner join CTE c 
on c.rn=c1.rn+1 
) 

select Date,UserCountToday,CASE WHEN rn<=7 then UserCount7days else (UserCount7days-(select UserCount7days from CTERec where rn=c.rn-7)) end asUserCount7days from CTERec c 
相關問題