繁体   English   中英

获取一周的第一天 T-SQL

[英]Get first day of week T-SQL

如何获得一周的第一天(星期一),其中周 = 6 年 = 2020 我需要得到 10.02.2020

例如。 2020 年第 1 周的日期为 06.01.2020 - 12.01.2020 2020 年第 6 周的日期为 10.02.2020 - 16.02.2020

DECLARE @YEAR int = 2020;
DECLARE @WEEKSTOADD int = 6;
SET DATEFIRST 1;

SELECT 
        DATEADD(day, 
                1 -  DATEPART(dw,DATEADD(week,@WEEKSTOADD,cast(cast(@YEAR as varchar(4)) + '0101' as date))), 
                DATEADD(week,@WEEKSTOADD,cast(cast(@YEAR as varchar(4)) + '0101' as date)))

无论DateFirstLanguage的设置如何,以下代码都将获取给定日期所在周的星期一日期:

Cast( DateAdd( day, - ( @@DateFirst + DatePart( weekday, Datum ) - 2 ) % 7, Datum ) as Date )

示例数据示例:

with SampleData as (
  select GetDate() - 30 as Datum
  union all
  select DateAdd( day, 1, Datum )
    from SampleData
    where Datum < GetDate() )
select Datum,
  -- 1 = Monday through 7 = Sunday.
  ( @@DateFirst + DatePart( weekday, Datum ) - 2 ) % 7 + 1 as WeekDay,
  -- Date of Monday in the week of the supplied date.
  Cast( DateAdd( day, - ( @@DateFirst + DatePart( weekday, Datum ) - 2 ) % 7, Datum ) as Date ) as Monday
  from SampleData;

根据示例数据,您需要substring()

select t.*, substring(datnum, charindex(' ', datnum) + 1, 10) as dt
from table t
where t.week = 6;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM