从SQL中的日期范围中提取整周和剩余天数

时间:2016-07-14 07:17:46

标签: sql tsql date-difference sql-date-functions

我的日期范围为1-Jul-201610-Jul-2016。我想提取该范围内的周数和剩余天数,如

No. of Weeks = 1 

No. of Remaining Days = 3

我知道如何使用

找到日期或星期差异
DATEDIFF(DAY,@ArrivalDate,@DepartureDate)
DATEDIFF(WEEK,@ArrivalDate,@DepartureDate)

但是如何查找并获取日期是否仅包含完整的周数或周和日。

任何帮助都将受到高度赞赏。

2 个答案:

答案 0 :(得分:1)

尝试以下查询

DECLARE @StartDate DATETIME = '2016.07.01'
DECLARE @EndDate DATETIME = '2016.07.10'

SELECT 
    DATEDIFF(DAY, @StartDate, @EndDate) / 7 AS 'No. of Weeks', -- 1
    (DATEDIFF(DAY, @StartDate, @EndDate) % 7) + 1 AS 'No. of Remaining Days' -- 3

答案 1 :(得分:0)

DECLARE @StartDate DATETIME = '2016.07.01'
DECLARE @EndDate DATETIME = '2016.07.10'

SELECT 
    -- DATEDIFF(DAY, @StartDate, @EndDate) / 7 AS 'No. of Weeks', -- 1
    DATEDIFF(WEEK, @StartDate, @EndDate) AS 'No. of Weeks',
   (DATEDIFF(DAY, @StartDate, @EndDate) % 7) + 1 AS 'No. of Remaining Days' -- 3