每周分组数据

时间:2015-06-05 07:41:52

标签: sql sql-server tsql

我遇到了以下问题。如何按照每周累计计数的方式对以下数据进行分组。

    +---------------------+-----+
    |          data       |count| 
    +---------------------+-----+
    | 2012-08-01 00:00:00 |  4  | 
    | 2012-08-02 00:00:00 |  5  | 
    | 2012-08-03 00:00:00 |  6  | 
    | 2012-08-04 00:00:00 |  6  | 
    | 2012-08-05 00:00:00 |  8  | 
    | 2012-08-06 00:00:00 |  6  | 
    | 2012-08-07 00:00:00 |  8  | 
    | 2012-08-08 00:00:00 |  6  | 
    | 2012-08-09 00:00:00 |  2  | 
    | 2012-08-10 00:00:00 |  0  | 
    | 2012-08-11 00:00:00 |  5  | 
    | 2012-08-12 00:00:00 |  4  | 
    | 2012-08-13 00:00:00 |  4  | 
    | 2012-08-14 00:00:00 |  0  |        
    +---------------------+-----+

输出应该是

+----------------------+------+
|     data             | count| 
+--------------------- +------+
| 2012-08-06 00:00:00  |  43  | 
| 2012-08-13 00:00:00  |  21  |
+----------------------+------+

1 个答案:

答案 0 :(得分:2)

你只需要使用" rounds"所有日期到你想要的日期,也许是这样的:

select
    DATEADD(week, DATEDIFF(week,0,data), 0) as Monday,
    sum([count]) as [count]
from
    yourtable
group by
    DATEADD(week, DATEDIFF(week,0,data), 0)