在SQL中显示星期的开始日期

时间:2017-07-13 12:50:00

标签: sql sql-server

我有一个SQL查询,用于返回每周的项目数。我有一个查询返回到目前为止:

Number of Items  |  Week Number
-------------------------------
        100      |     18
        80       |     19
        120      |     20

并希望返回以下内容:

Number of Items  |  Week Beginning
-------------------------------
        100      |     1st May 2017
        80       |     8th May 2017
        120      |     15th May 2017

到目前为止我所拥有的是:

SELECT COUNT(*) AS 'Number of Items', DATEPART(WEEK, Date) FROM table
where DATEPART(Year, Date) = '2017' and DATEPART(MONTH, Date) = 5
group by DATEPART(WEEK, Date)

4 个答案:

答案 0 :(得分:0)

你说的是本周的第一天:

int_ptr_wrapper(int value = 0){
mInt = new int(value);
}

答案 1 :(得分:0)

因为你需要星期一成为一周的第一天

select  DATEPART(WEEK, MyDate),DATEADD(DAY,1,(DATEADD(DAY, 1-DATEPART(WEEKDAY, MyDate), MyDate)))
    from (
    select '5/3/2017' MyDate
    union all select '5/10/2017'
    union all select '5/14/2017')A

答案 2 :(得分:0)

SELECT DATEADD(DAY, DATEDIFF(DAY, 0, Date) /7*7, 0) AS StartDateOfWeek

答案 3 :(得分:0)

如果它解决了,请检查

DECLARE @WeekNum INT
      , @YearNum char(4);

SELECT @WeekNum = 20 
     , @YearNum = 2017
-- once you have the @WeekNum and @YearNum set, the following calculates the date range.
SELECT DATEADD(wk, DATEDIFF(wk, 6, '1/1/' + @YearNum) + (@WeekNum-1), 6) AS StartOfWeek;
SELECT DATEADD(wk, DATEDIFF(wk, 5, '1/1/' + @YearNum) + (@WeekNum-1), 5) AS EndOfWeek;

感谢http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=185440