• You probably want to do something like this then:

    WITH SampleData AS

    (

    SELECT userid, [date], usage

    FROM

    (

    VALUES ('cjohn','2013/10/01 00:30:00',5)

    ,('fpears','2013/10/03 00:11:00',2)

    ,('cjohn','2013/10/04 12:30:45',3)

    ,('kthomas','2013/10/04 13:20:11',3)

    ,('cjohn','2013/10/04 14:10:10',2)

    ,('rpeter','2013/10/04 18:01:01',3)

    ,('cjohn','2013/10/04 19:10:01',10)

    ,('fpears','2013/10/06 19:11:11',11)

    ,('cjohn','2013/10/07 10:11:03',20)

    ,('rpeter','2013/10/09 05:10:05',11)

    ,('fpears','2013/10/11 06:10:15',6)

    ,('cjohn','2013/10/14 13:11:11',7)

    ,('kthomas','2013/10/16 08:10:10',6)

    ) a (userid, [date], usage)

    )

    SELECT userid, [date]=CAST([date] AS DATE), usage

    INTO #Temp

    FROM SampleData

    -- By day

    SELECT [date], AvgUsage=(1.0 * SUM(usage)) / COUNT(DISTINCT userid)

    FROM #Temp

    GROUP BY [date];

    -- By week

    SELECT [week]=DATEADD(week, DATEDIFF(week, 0, [date]), 0)

    ,AvgUsage=(1.0 * SUM(usage)) / COUNT(DISTINCT userid)

    FROM #Temp

    GROUP BY DATEADD(week, DATEDIFF(week, 0, [date]), 0);

    -- By month

    SELECT [month]=DATEADD(month, DATEDIFF(month, 0, [date]), 0)

    ,AvgUsage=(1.0 * SUM(usage)) / COUNT(DISTINCT userid)

    FROM #Temp

    GROUP BY DATEADD(month, DATEDIFF(month, 0, [date]), 0);

    -- By year

    SELECT [month]=DATEADD(year, DATEDIFF(year, 0, [date]), 0)

    ,AvgUsage=(1.0 * SUM(usage)) / COUNT(DISTINCT userid)

    FROM #Temp

    GROUP BY DATEADD(year, DATEDIFF(year, 0, [date]), 0);

    SELECT DATEADD(week, DATEDIFF(week, 0, '2013-09-28'), 0) -- This is Sat

    ,DATEADD(week, DATEDIFF(week, 0, '2013-09-29'), 0) -- This is Sun

    ,DATEADD(week, DATEDIFF(week, 0, '2013-09-30'), 0) -- This is Mon

    GO

    DROP TABLE #Temp;

    The only thing tricky about this is the week reporting. The final select shows that Sundays are reported in the same week as the following Monday, but the date returned by the DATEADD construct is the Monday. This is going to be sensitive to your setting for DATEFIRST.

    Play around with it and see if it helps.


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St