如何在T-SQL中查找给定时间间隔内的星期数

时间:2019-06-14 09:08:20

标签: sql sql-server

我有点卡在这里,我想查找给定时间间隔内的所有星期数,但我真的无法弄清楚

例如,代替  - > datepart(week,dateadd(day,-1,@oneSingleDate))(星期一是一周的第一天),

我需要

- > datepart(week,@startDate,@endDate) 

鉴于间隔'2019-01-04'-'2019-01-28',输出必须为:

WeekNo:1,2,3,4,5

2 个答案:

答案 0 :(得分:0)

我使用了递归CTE来生成范围内的所有日期,然后我使用DATEPART从中选择了DISTINCT周数。然后,我将您的逗号分隔的字符串连接到一个名为@OUT

的变量中
DECLARE @startDate as date = '20190104';
DECLARE @endDate as date = '2019-01-28';

DECLARE @OUT as nvarchar(max);

WITH CTE AS (SELECT @startDate As X
             UNION ALL
             SELECT DATEADD(y, 1, X) X FROM CTE where x < @endDate),
    CTE2 AS (SELECT DISTINCT datepart(wk, X) wk from cte)
    select @out = coalesce(@out + ', ', '') + cast(wk as nvarchar(4))  from cte2
    OPTION (MAXRECURSION 0);

    select @out;

答案 1 :(得分:0)

您可以执行以下操作: 使用:  -[CTE] [1]常用表格表达  -[Sql递归联合全部] [2]  -[将多行串联成一行] [3]

declare @startDate as date ;
declare @endDate as date ;
set @startDate='2019-01-04'; 
set @endDate='2019-01-28' ;
DECLARE @weeks VARCHAR(8000) ;
with cte as (select @startDate as mydate,datepart(week,@startDate) w
union all select
dateadd(day,1,mydate),datepart(week,dateadd(day,1,mydate))  from cte
where mydate < @endDate) , cte2 as (select distinct(w) from cte)
select @weeks=COALESCE(@weeks + ', ', '') +cast(w as varchar(2)) from
cte2 OPTION (MAXRECURSION 360) select @weeks [Result]