简体   繁体   中英

How to calculate previous year same day of week from month suppose first Monday of month would be last year first Monday of that month

How to calculate same day of week from last year like first Monday of May this year would be last year first Monday of May and so on for all days.

SELECT 
    ADD_MONTHS(CURRENT_DATE, -12) + 
        ((SELECT day_of_week 
          FROM sys_calendar.calendar 
          WHERE calendar_date = CURRENT_DATE) -
          (SELECT day_of_week 
           FROM sys_calendar.calendar 
           WHERE calendar_date = ADD_MONTHS(CURRENT_DATE, -12)))

I did the above thing but for the dates like 7th April 2021 is 1st Wednesday from month is taking 8th April 2020 which is 2nd Wednesday from month but I want 1st April 2020 to be calculated.

Sample is

2021/4/7 to 2020/4/1
2021/4/14 to 2020/4/8

This kind of calculations I want

I have a suggestion which may be usable for you, despite of all correct comments and queries above.
If what you said is a common query in your system and it is not what you want to query JUST FOR NOW, I suggest you to create a Dim_Date in your database and use it to find information about your date without using complicated slow queries. This is what comes from my exprience I hope it helps.


I also searched and found a good table for you in the link below. It is a xlsx file which is attached at the end of the article. Download and import to your database then use it with code below.
Date Dimension File


The Code I used was this:

WITH X AS (
SELECT
--- The Number You Want ----
ROW_NUMBER() OVER (PARTITION BY YearMonthNum,DayName ORDER BY DateNum) AS DayWeekNumber 
    ,YearMonthNum
    ,DayName
    ,Date
    ,DateNum
    ,MonthNum
    ,DayNumOfWeek
    ,Year
FROM dbo.dimDate Dim --- The Excel I imported
) 
SELECT DISTINCT * 
FROM X X1
JOIN dbo.MyTable T1 -- My Table And my Date Column
    ON T1.myDate = X1.Date
JOIN X X2 ON X2.Year = X1.Year-1   -- I wanted last year match so (-1). use (-n) for n years ago  
            AND X2.MonthNum = X1.MonthNum
            AND X2.DayNumOfWeek = X1.DayNumOfWeek
            AND X2.DayWeekNumber = X1.DayWeekNumber

这是结果图像

The answer to this question is not going to be an easy one. It will most likely require a lookup table providing the weekday of each first day of the month for some years. From there the remaining calculations can be developed.

In that sense, this post is not going to be an "answer" but rather a longer comment which needs some formatting and a snippet for illustration.

When playing around in JavaScript I found a fairly direct way of doing this kind of n-th weekday calculation for a given year and month (this could be used to calculate a suitable lookup-table for your database):

 function createDate2(a){ // [2020,3,1,3] = [year,month,weekday, n-th occurence of weekday in month] const d=new Date(a[0],a[1],1); // create first day of the month d.setDate((a[2]-d.getDay()-6)%7 + a[3]*7); // adjust to a[3]-th occurrence of the given weekday a[2] return d } // weekday numbering: 0-Sunday, 1-Monday, 2-Tuesday... 6-Saturday // extend the Date prototype: Date.prototype.getDate2=function(){ return [this.getFullYear(),this.getMonth(),this.getDay(),-~(this.getDate()/7)]; } // returns an array: [year,month,weekday, n-th occurence of weekday in month] // calculate the third Thursday in each month for 2023: for (let d,m=0;m<12;m++) console.log(createDate2([2023,m,4,3]).toLocaleDateString("en-US",{weekday:'long',year:'numeric',month:'long',day:'numeric'}) );

Maybe it is still useful for someone? ... For example, in extracting some parts of it for an SQL-based answer?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM