Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 从给定日期开始计算过去7天的用户数_Sql Server_Dateadd - Fatal编程技术网

Sql server 从给定日期开始计算过去7天的用户数

Sql server 从给定日期开始计算过去7天的用户数,sql-server,dateadd,Sql Server,Dateadd,我有一个表格,其中我必须更新该特定日期的用户数量以及从给定日期起过去7天的用户数量。示例数据看起来像 Date UserCountToday UserCount7days 20120911 907575 20120910 953629 20120909 1366180 20120908 1388916 20120907 1009425 20120906 918638 20120905 956770 20120904 1

我有一个表格,其中我必须更新该特定日期的用户数量以及从给定日期起过去7天的用户数量。示例数据看起来像

Date    UserCountToday  UserCount7days
20120911    907575  
20120910    953629  
20120909    1366180 
20120908    1388916 
20120907    1009425 
20120906    918638  
20120905    956770  
20120904    1018152 
20120903    1306341 
试试这个:

 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

对不起,我不明白你的问题我们有没有更快捷的方法来处理这个问题?我有大量的数据。日期范围从今天到过去的18个月。这是一种相同的查询,但我希望每个时期都有不同的用户。早些时候,我对过去7天的UserCountToday列进行了合计,但它应该是不同用户的合计。我知道我只需要输入countdistinct userid,但这需要花费很多时间:
 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