Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the last day of the week

I have a table with a bunch of dates (option maturity dates to be precise). I need to query this database to find the last day of a specific week that is stored in the table.

All I will be given to query this table is the year, the month and the specific week. And based on this I need to find the date that is stored in the table that matches this.

I've created the following query to find this specific date March 28 2013

SELECT M_SETNAME, M_LABEL, M_MAT FROM OM_MAT_DBF
WHERE M_SETNAME = 'IMM_OSET  '
AND MONTH(M_MAT) = 3
AND YEAR(M_MAT) = 2013
AND ((DATEPART(day,M_MAT)-1)/7 + 1) = 5

Do you guys have any idea of how I can change the last condition so that March 28th will be considered the 5th week of the month and not the 4th week as it is currently doing.

like image 568
user3284817 Avatar asked Feb 10 '14 19:02

user3284817


People also ask

What is the day at the end of the week?

Sunday is the 7th and last day of the week. Although this is the international standard, several countries, including the United States and Canada, consider Sunday as the start of the week.

How do you figure out what day of the week a date is?

For a Gregorian date, add 0 for 1900's, 6 for 2000's, 4 for 1700's, 2 for 1800's; for other years, add or subtract multiples of 400. For a Julian date, add 1 for 1700's, and 1 for every additional century you go back. Add the last two digits of the year. Divide by 7 and take the remainder.

How do I get the last day of the week in SQL?

Replace GETDATE() with a parameter @date to get the last Sunday before a particular date.


1 Answers

You can also use DATEPART to get the number of the week (in the year), but then, you could also get the 1st of each month, and take the week too so you can have: WEEK OF MY DATE - WEEK OF FIRST DAY FOR THIS MONTH + 1.

Here you have an example...

DECLARE @Dt datetime

SELECT @Dt='03-28-2013'

SELECT DATEPART( wk, @Dt) - DATEPART( wk, Convert(Date,Convert(varchar(4),YEAR(@Dt))
+ '-' + Convert(varchar(2), MONTH(@Dt))
+ '-' + Convert(varchar(2), 1))) + 1

EDIT: Also, looking at your code, you could add the CEILING. If the result == 2.7, it means it passed the 2nd week, however, it gets rounded to 2 when it should actually be 3.

If you add the CEILING and the CONVERT to decimal should work..

SELECT  MONTH(@Dt), 
        YEAR(@Dt), 
        ((CEILING(Convert(decimal,DATEPART(day,@Dt)-1)/7)) + 1) 
like image 61
Yumei De Armas Avatar answered Oct 01 '22 23:10

Yumei De Armas