如何在SQL中获取给定月份的日期总周数

时间:2017-04-03 12:22:25

标签: sql sql-server sql-server-2008

尊敬的专家,

根据我们公司的要求,我们需要关注任何月份的周细节

e.g。 如果月份 4月且年份 2017 ,则查询结果应为

weeknumber     startdate     enddate 
    1         01-04-2017   01-04-2017    
    2         02-04-2017   08-04-2017
    3         09-04-2017   15-04-2017
    4         16-04-2017   22-04-2017
    5         23-04-2017   29-04-2017
    6         30-04-2017   30-04-2017

通过搜索,我只能计算一个月的周数,但我需要开始和结束它应该从周日到周六开始。

非常感谢你。

2 个答案:

答案 0 :(得分:3)

如果您只想让一个函数返回一个月的一个月,那么这可以达到您想要的效果:

create function dbo.udf_weeks_of_month (@fromdate date) 
returns table with schemabinding as return (
with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
, dates as (
  select top (datediff(day, @fromdate, dateadd(month, datediff(month, 0, @fromdate )+1, 0))) 
    [DateValue]=convert(date,dateadd(day,row_number() over(order by (select 1))-1,@fromdate))
  from n as deka cross join n as hecto
)
select 
    WeekOfMonth = row_number() over (order by datepart(week,DateValue))
  , WeekStart   = min(DateValue)
  , WeekEnd     = max(DateValue)
from dates
group by datepart(week,DateValue)
);

并像这样调用它:

set datefirst 7;
select 
    WeekOfMonth
  , WeekStart 
  , WeekEnd   
from dbo.udf_weeks_of_month('20170401');

返回:

+-------------+------------+------------+
| WeekOfMonth | WeekStart  |  WeekEnd   |
+-------------+------------+------------+
|           1 | 2017-04-01 | 2017-04-01 |
|           2 | 2017-04-02 | 2017-04-08 |
|           3 | 2017-04-09 | 2017-04-15 |
|           4 | 2017-04-16 | 2017-04-22 |
|           5 | 2017-04-23 | 2017-04-29 |
|           6 | 2017-04-30 | 2017-04-30 |
+-------------+------------+------------+

rextester演示:http://rextester.com/FSA98744(注意:rextester重新格式化日期)

使用日历表而不是函数可以轻松处理。

参考:

答案 1 :(得分:0)

这样做(它不依赖于set datefirst):

-- can be any date within the month
DECLARE @d date = '2017-04-01'
SET @d = dateadd(mm,datediff(mm,0,@d),0)
;WITH CTE(dat) as
(
  SELECT top(datediff(d, @d, dateadd(mm,1, @d)))
    cast(dateadd(d, row_number() over(order by (SELECT null))-1, @d) as date)
  FROM
    (values(0),(0),(0),(0),(0),(0)) s(n),
    (values(0),(0),(0),(0),(0),(0)) t(n)
)
SELECT 
 datediff(week, @d,dat)+1 wk,
 min(dat) startdate,
 max(dat) enddate
FROM CTE
GROUP BY datediff(week, @d,dat)

结果:

wk  startdate   enddate
1   2017-04-01  2017-04-01
2   2017-04-02  2017-04-08
3   2017-04-09  2017-04-15
4   2017-04-16  2017-04-22
5   2017-04-23  2017-04-29
6   2017-04-30  2017-04-30