如何获得周开始和结束日期?

时间:2014-07-30 14:06:24

标签: sql sql-server tsql

我有一个名为WeekBeginDate的变量,我只想提取该周的数据。例如,如果星期日的开头为07/21/2014,在这种情况下为Monday,那么我只想将数据从07/21/2014提取到7/27/2014

变量将始终仅包含星期开头的日期,但我没有星期结束的日期。

本周从Monday开始,到Sunday结束。如果我只有一周的开始日期,我无法弄清楚如何计算或总和小时数。

SELECT DT, sum (TOT_HOURS)as TOT_HOURS FROM MYTABLE where DT >= @WeekBeginDate and <=@WeekEndDate group by DT

请注意,我只有WeekBeginDate的变量。

6 个答案:

答案 0 :(得分:1)

只需修改此CTE中的表格列即可:

;WITH workhours AS
(
    SELECT  DATEADD(DAY
                ,   -(DATEPART(dw, DT) -1)
                ,   DT) AS week_start
        ,   DATEADD(DAY
                ,   7 - (DATEPART(dw, DT))
                ,   DT) AS week_end

    FROM    MYTABLE
)
SELECT      week_start
        ,   week_end
        ,   SUM(TOT_HOURS) total_hrs_per_week
FROM        workhours
GROUP BY    week_start
        ,   week_end

答案 1 :(得分:1)

您可能需要在本周开始时添加6天 如果你需要每周总时数,我可以通过其他方式进行分组,我可以将其称为&#34; id&#34;。 不是通过dt(或者根本没有组合,如果它是整个表的总数):

SELECT id, DT, sum (TOT_HOURS)as TOT_HOURS FROM MYTABLE 
where DT BETWEEN @WeekBeginDate and DATEADD(d,6,@WeekBeginDate)
GROUP BY id

答案 2 :(得分:1)

这应该对你有用。我到目前为止正在考虑这一天的24小时。

DECLARE @WeekBeginDate DATETIME

SET @WeekBeginDate = '2014-07-28 12:08:31.633';
WITH MYTABLE (DT,TOT_HOURS)
    AS (
    SELECT '2014-06-27 00:08:31.633',5 UNION ALL
    SELECT '2014-07-27 00:08:31.633',5 UNION ALL
    SELECT '2014-07-28 00:08:31.633',1 UNION ALL
    SELECT '2014-07-29 00:08:31.633',1 UNION ALL
    SELECT '2014-07-30 00:08:31.633',1 UNION ALL
    SELECT '2014-07-31 00:08:31.633',1 UNION ALL
    SELECT '2014-08-01 00:08:31.633',1 UNION ALL
    SELECT '2014-08-02 00:08:31.633',1 UNION ALL
    SELECT '2014-08-03 00:08:31.633',1
    )
SELECT  CAST(@WeekBeginDate AS DATE) AS StartDate,
       DATEADD(d, 6, CAST(@WeekBeginDate AS DATE)) AS EndDate,
       SUM (TOT_HOURS)AS TOT_HOURS
FROM MYTABLE
WHERE CAST(DT AS DATE) BETWEEN CAST(@WeekBeginDate AS DATE) AND DATEADD(d, 6, CAST(@WeekBeginDate AS DATE))

答案 3 :(得分:0)

只需添加6(或7)天......

SELECT DT, sum (TOT_HOURS)as TOT_HOURS FROM MYTABLE 
where DT BETWEEN @WeekBeginDate and @WeekBeginDate + 6 group by DT

答案 4 :(得分:0)

选择@weekBeginDate = DATEADD(wk,DATEDIFF(wk,0,GETDATE()),0)

选择@WeekEndDate = DATEADD(dd,6,DATEADD(wk,DATEDIFF(wk,0,GETDATE()),0))

SELECT DT,sum(TOT_HOURS)为TOT_HOURS FROM MYTABLE,其中DT&gt; = @WeekBeginDate和&lt; = @ WeekEndDate group by DT

答案 5 :(得分:0)

这里有一个日历表非常有用, 特别是如果星期一是假期你的逻辑需要改变。

基本上创建一个包含数周预先计算值的表,然后加入它。

http://www.made2mentor.com/2011/04/calendar-tables-why-you-need-one