Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

sql server - SQL query to find dates of last year equivalent to today's date

I am writing a SQL query to find business working dates of last year equivalent to today's date.

In this query it should fetch :-

For e.g. if today is 5th January, 2021 and it is the second day of second week of the year. So I need to find the exact equivalent date of the second day of second week of the previous year. So it would be 7th January, 2020.

And with this, I need the business working dates of that week of 7th January 2020 (i.e. excluding Saturday & Sunday) Which will come up as 2020-Jan-06 to 2020-Jan-10 according to the example.

So I will need the report between 6th Jan - 10th Jan, 2020.

I am trying to use this code to find date of last year equivalent to today's date (5th Jan, 2021 viz. second day of second week)

select Convert(date, (DATEADD(year, -1, getdate()+2))) ;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have use multiple CTE to show you the step by step calculation. It should be pretty easy to follow.

Basically it find the week_no and day_no_of_week for 2021-01-05 and then use that to find the same date for 2020

declare @input_date     date = '2021-01-05',
        @year_offset    int  = -1;  -- previous year

with 
cte1 as
(
    select  input_date          = @input_date,
            week_no             = DATEPART(WEEK, @input_date),
            first_day_of_week   = DATEADD(WEEK, DATEDIFF(WEEK, 0, @input_date), 0)
),
cte2 as
(
    select  *,
            day_no_of_week = DATEDIFF(DAY, first_day_of_week, @input_date) + 1
    from    cte1 
),
cte3 as
(
    select  *,
            first_day_of_the_prev_year = DATEADD(YEAR, DATEDIFF(YEAR, 0, @input_date) + @year_offset, 0)
    from    cte2
),
cte4 as
(
    select  *,
            first_day_of_week_prev_year = DATEADD(WEEK, DATEDIFF(WEEK, 0, DATEADD(WEEK, week_no - 1, first_day_of_the_prev_year)), 0)
    from    cte3
)
select  *,
        DATEADD(DAY, day_no_of_week - 1, first_day_of_week_prev_year) as the_required_date
from    cte4

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...