如何转换以下查询以给出每周的总和

时间:2015-08-07 09:27:12

标签: sql sql-server sql-server-2008 sql-server-2005

这是计算每天总时间的长查询的一部分。我想改变它给我每周的总时间。任何的想法?要查看长查询,请点击Here

INSERT INTO @test (
    activity
    ,DATE
    ,TimePerDay
    )
SELECT activity
    ,Cast(starttime AS DATE) AS DATE
    ,SUM(datediff(second, starttime, endtime)) / 60.0 AS TimePerDay
FROM cte WITH (NOLOCK)
WHERE starttime >= dateadd(week, @LastXWeeks, last_update)
GROUP BY activity
    ,cast(starttime AS DATE)

1 个答案:

答案 0 :(得分:1)

你可以这样做:

SELECT activity
    ,DATEADD(wk, DATEDIFF(wk,0,Cast(starttime AS DATE)), 0) AS Week
    ,SUM(datediff(second, starttime, endtime)) / 60.0 AS TimePerDay
FROM cte WITH (NOLOCK)
WHERE starttime >= dateadd(week, @LastXWeeks, last_update)
GROUP BY activity
    ,DATEADD(wk, DATEDIFF(wk,0,Cast(starttime AS DATE)), 0)

您可能需要根据每周实际开始的日期调整代码。这适用于周一至周日。