2017-04-03 134 views
0

尊敬的專家,如何總週日期爲給定月份獲得SQL

根據我們公司的要求,我們需要幾個星期的詳細信息任何一個月

例如 如果一個月是四月和年是比查詢結果應該是

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 

隨着我只能在一個月算周搜索,但我需要開始日期和結束日期應該是開始從週日到週六。

非常感謝您提前。

+3

你嘗試過到現在怎麼辦?請發佈 –

+4

我投票結束這個問題,因爲OP沒有表現出任何努力。 – Darren

+0

Weeknumber 3兩次? – jarlh

回答

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重新格式化日期)


這可以用日曆表而非函數輕鬆處理。

參考:

+0

非常感謝您先生這是我們正在尋找! –

+0

@ user3414865樂意幫忙! – SqlZim

+0

@SqlZim:當OP通過01042017即每月的第一天時,您的功能是否有效?如果OP提供當月的任何日期,會發生什麼情況? –

0

這將做到這一點(它不依賴於一套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 
相關問題