Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to weekly group if you have daily data

I'm currently stuck with this problem. Suppose I have the following daily data

    +-------------------------+-----+----+
    |          Date           | C1  | C2 |
    +-------------------------+-----+----+
    | 2012-08-01 00:00:00.000 |  44 | 44 |
    | 2012-08-02 00:00:00.000 |  51 | 49 |
    | 2012-08-03 00:00:00.000 |  60 | 59 |
    | 2012-08-04 00:00:00.000 |  68 | 67 |
    | 2012-08-05 00:00:00.000 |  82 | 78 |
    | 2012-08-06 00:00:00.000 |  62 | 59 |
    | 2012-08-07 00:00:00.000 |  58 | 53 |
    | 2012-08-08 00:00:00.000 |  69 | 65 |
    | 2012-08-09 00:00:00.000 |  82 | 72 |
    | 2012-08-10 00:00:00.000 |  70 | 68 |
    | 2012-08-11 00:00:00.000 |  75 | 71 |
    | 2012-08-12 00:00:00.000 |  64 | 64 |
    | 2012-08-13 00:00:00.000 |  74 | 69 |
    | 2012-08-14 00:00:00.000 |  60 | 56 |
    | 2012-08-15 00:00:00.000 |  66 | 60 |
    | 2012-08-16 00:00:00.000 |  57 | 51 |
    | 2012-08-17 00:00:00.000 |  52 | 49 |
    +-------------------------+-----+----+

How will I group it in such a way that it will sum up C1 and C2 by weekly basis? Expected output should be

+---------------------------+------+----+
|          Date             |  C1  | C2 |
+---------------------------+------+----+
| 2012-08-06 to 2012-12-12  |  480 | 452|
| 2012-08-13 to 2012-08-19  |  430 | 394|
+---------------------------+------+----+

It started with 2012-08-06 since the cycle should be Monday to Sunday. I've tried googling about an hour or so and it seems that no result fits with my problem, I Hope someone could help me.

Thanks!

like image 222
Sherwin Avatar asked Sep 18 '12 06:09

Sherwin


1 Answers

try this:

SET DATEFIRST 1 will set your start of the week to Monday

SET DATEFIRST 1

    SELECT CAST(MIN( [DATE]) AS VARCHAR(20))+' TO '+CAST (MAX([DATE]) AS VARCHAR(20)) AS DATE,
           SUM(C1) AS GRU,
           SUM(C2) AS C1
    FROM   YOUR_TABLE
    GROUP BY DATEPART(WEEK,[DATE])
    HAVING COUNT(DISTINCT[DATE])=7

SET DATEFIRST 7
like image 130
Joe G Joseph Avatar answered Nov 15 '22 20:11

Joe G Joseph