获取Weekstartdate并按日期结束

时间:2016-07-27 00:27:03

标签: sql-server-2008 tsql

如何通过传递weekstartdate来获取weekenddatedate

当我通过2016-07-27 01:24:10.510时,我需要此输出

startdate:2016-07-24 00:00:00.000Sunday enddate:2016-07-30 00:00:00.000Saturday

我使用了这段代码,但这会返回错误的输出

DECLARE @Date DATE = getdate()

SELECT  d.WeekStart,
    Weekend = CASE WHEN DATEADD(DAY, 7, WeekStart) > StartOfNextMonth
                        THEN StartOfNextMonth
                    ELSE DATEADD(DAY, 7, WeekStart)
                END
FROM    (   SELECT  WeekStart = DATEADD(DAY, 
                                    ((DATEPART(DAY, @Date) - 1) / 7.0) * 7, 
                                    DATEADD(MONTH, DATEDIFF(MONTH, 0, @Date), 0)),
                StartOfNextMonth = DATEADD(MONTH, DATEDIFF(MONTH, 0, @Date) + 1, 0)
    ) AS d;

任何想法?

2 个答案:

答案 0 :(得分:0)

假设@@DATEFIRST7

declare @Samples as Table ( Sample DateTime );
insert into @Samples ( Sample ) values
  ( '2016-07-27 01:24:10.510' ),
  ( '2016-07-20 00:00:00.000' ),
  ( '2016-07-21 00:00:00.000' ),
  ( '2016-07-22 00:00:00.000' ),
  ( '2016-07-23 00:00:00.000' ),
  ( '2016-07-24 00:00:00.000' ),
  ( '2016-07-25 00:00:00.000' ),
  ( '2016-07-26 00:00:00.000' ),
  ( '2016-07-27 00:00:00.000' ),
  ( '2016-07-28 00:00:00.000' ),
  ( '2016-07-29 00:00:00.000' );

select Sample,
  DateAdd( day, 1 - DatePart( weekday, Sample ), Cast( Sample as Date ) ) as [StartOfWeek],
  DateAdd( day, 7 - DatePart( weekday, Sample ), Cast( Sample as Date ) ) as [EndOfWeek]
  from @Samples;

答案 1 :(得分:0)

也可以是表格值函数

Declare @Date Date = GetDate()

Select weekstartdate = DateAdd(DD,1-DatePart(DW,@Date),@Date ) 
      ,weekenddate   = DateAdd(DD,7-DatePart(DW,@Date),@Date ) 

返回

weekstartdate   weekenddate
2016-07-24      2016-07-30