How to get week number of the month from the date in sql server 2008 - sql-server-2008

In SQL Statement in microsoft sql server, there is a built-in function to get week number but it is the week of the year.
Select DatePart(week, '2012/11/30') // **returns 48**
The returned value 48 is the week number of the year.
Instead of 48, I want to get 1, 2, 3 or 4 (week number of the month). I think the week number of the month can be achieved by modules with Month Number of this week. For e.g.
Select DATEPART(week, '2012/11/30')%MONTH('2012/11/30')
But I want to know is there other built-in functions to get WeekNumber of the month in MS SQL SERVER.

Here are 2 different ways, both are assuming the week starts on monday
If you want weeks to be whole, so they belong to the month in which they start:
So saturday 2012-09-01 and sunday 2012-09-02 is week 4 and monday 2012-09-03 is week 1 use this:
DECLARE #date date = '2012-09-01'
SELECT (day(datediff(d,0,#date)/7*7)-1)/7+1
If your weeks cut on monthchange so saturday 2012-09-01 and sunday 2012-09-02 is week 1 and monday 2012-09-03 is week 2 use this:
DECLARE #date date = '2012-09-01'
SELECT
datediff(ww,datediff(d,0,dateadd(m,datediff(m,7,#date),0)
)/7*7,dateadd(d,-1,#date))+1
I received an email from Gerald. He pointed out a flaw in the second method. This should be fixed now
I received an email from Ben Wilkins. He pointed out a flaw in the first method. This should be fixed now

DECLARE #DATE DATETIME
SET #DATE = '2013-08-04'
SELECT DATEPART(WEEK, #DATE) -
DATEPART(WEEK, DATEADD(MM, DATEDIFF(MM,0,#DATE), 0))+ 1 AS WEEK_OF_MONTH

No built-in function. It depends what you mean by week of month. You might mean whether it's in the first 7 days (week 1), the second 7 days (week 2), etc. In that case it would just be
(DATEPART(day,#Date)-1)/7 + 1
If you want to use the same week numbering as is used with DATEPART(week,), you could use the difference between the week numbers of the first of the month and the date in question (+1):
(DATEPART(week,#Date)- DATEPART(week,DATEADD(m, DATEDIFF(m, 0, #Date), 0))) + 1
Or, you might need something else, depending on what you mean by the week number.

Just look at the date and see what range it falls in.
Range 1-7 is the 1st week, Range 8-14 is the 2nd week, etc.
SELECT
CASE WHEN DATEPART(day,yourdate) < 8 THEN '1'
ELSE CASE WHEN DATEPART(day,yourdate) < 15 then '2'
ELSE CASE WHEN DATEPART(day,yourdate) < 22 then '3'
ELSE CASE WHEN DATEPART(day,yourdate) < 29 then '4'
ELSE '5'
END
END
END
END

Similar to the second solution, less code:
declare #date datetime = '2014-03-31'
SELECT DATEDIFF(week,0,#date) - (DATEDIFF(week,0,DATEADD(dd, -DAY(#date)+1, #date))-1)

Check this out... its working fine.
declare #date as datetime = '2014-03-10'
select DATEPART(week,#date) - DATEPART(week,cast(cast(year(#date) as varchar(4))+'-' + cast(month(#date) as varchar(2)) + '-01' as datetime))+1

WeekMonth = CASE WHEN (DATEPART(day,TestDate) - datepart(dw,TestDate))>= 22 THEN '5'
WHEN (DATEPART(day,TestDate) - datepart(dw,TestDate))>= 15 THEN '4'
WHEN (DATEPART(day,TestDate) - datepart(dw,TestDate))>= 8 THEN '3'
WHEN (DATEPART(day,TestDate) - datepart(dw,TestDate))>= 1 THEN '2'
ELSE '1'
END

There is no inbuilt function to get you the week number. I dont think dividing will help you anyway as the number of weeks in a month is not constant.
http://msdn.microsoft.com/en-us/library/bb675168.aspx
I guess you can divide the number(48) by 4 and take the modules of the same and project that as the week number of that month, by adding one to the result.

Here's a suggestion for getting the first and last days of the week for a month:
-- Build a temp table with all the dates of the month
drop table #tmp_datesforMonth
go
declare #begDate datetime
declare #endDate datetime
set #begDate = '6/1/13'
set #endDate = '6/30/13';
WITH N(n) AS
( SELECT 0
UNION ALL
SELECT n+1
FROM N
WHERE n <= datepart(dd,#enddate)
)
SELECT DATEADD(dd,n,#BegDate) as dDate
into #tmp_datesforMonth
FROM N
WHERE MONTH(DATEADD(dd,n,#BegDate)) = MONTH(#BegDate)
--- pull results showing the weeks' dates and the week # for the month (not the week # for the current month)
select MIN(dDate) as BegOfWeek
, MAX(dDate) as EndOfWeek
, datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, dDate), 0)), 0), dDate) as WeekNumForMonth
from #tmp_datesforMonth
group by datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, dDate), 0)), 0), dDate)
order by 3, 1

A dirty but easy one liner using Dense_Rank function. Performance WILL suffer, but effective none the less.
DENSE_RANK()over(Partition by Month(yourdate),Year(yourdate) Order by Datepart(week,yourdate) asc) as Week

Here is the query that brings the week number on whatever the startday and endday of the week it may be.
SET DATEFIRST 2
DECLARE #FROMDATE DATE='12-JAN-2015'
-- Get the first day of month
DECLARE #ALLDATE DATE=DATEADD(month, DATEDIFF(month, 0, #FROMDATE), 0)
DECLARE #FIRSTDATE DATE
;WITH CTE as
(
-- Get all dates in that month
SELECT 1 RNO,CAST(#ALLDATE AS DATE) as DATES
UNION ALL
SELECT RNO+1, DATEADD(DAY,1,DATES )
FROM CTE
WHERE DATES < DATEADD(MONTH,1,#ALLDATE)
)
-- Retrieves the first day of week, ie, if first day of week is Tuesday, it selects first Tuesday
SELECT TOP 1 #FIRSTDATE = DATES
FROM CTE
WHERE DATEPART(W,DATES)=1
SELECT (DATEDIFF(DAY,#FIRSTDATE,#FROMDATE)/7)+1 WEEKNO
For more information I have answered for the below question. Can check that.
How do I find week number of a date according to DATEFIRST

floor((day(#DateValue)-1)/7)+1

Here you go....
Im using the code below..
DATEPART(WK,#DATE_INSERT) - DATEPART(WK,DATEADD(DAY,1,DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,#DATE_INSERT),0)))) + 1

Try Below Code:
declare #dt datetime='2018-03-15 05:16:00.000'
IF (Select (DatePart(DAY,#dt)%7))>0
Select (DatePart(DAY,#dt)/7) +1
ELSE
Select (DatePart(DAY,#dt)/7)

There is an inbuilt option to get the week number of the year
**select datepart(week,getdate())**

You can simply get week number by getting minimum week number of month and deduct it from week number. Suppose you have a table with dates
select
emp_id, dt , datepart(wk,dt) - (select min(datepart(wk,dt))
from
workdates ) + 1 from workdates

Solution:
declare #dt datetime='2018-03-31 05:16:00.000'
IF (Select (DatePart(DAY,#dt)%7))>0
Select (DatePart(DAY,#dt)/7) +1
ELSE
Select (DatePart(DAY,#dt)/7)

declare #end_date datetime = '2019-02-28';
select datepart(week, #end_date) - datepart(week, convert(datetime, substring(convert(nvarchar, convert(datetime, #end_date), 127), 1, 8) + '01')) + 1 [Week of Month];

Here is the tried and tested solution for this query in any situation - like if 1st of the month is on Friday , then also this will work -
select (DATEPART(wk,#date_given)-DATEPART(wk,dateadd(d,1-day(#date_given),#date_given)))+1
above are some solutions which will fail if the month's first date is on Friday , then 4th will be 2nd week of the month

Logic here works as well 4.3 weeks in every month. Take that from the DATEPART(WEEK) on every month but January. Just another way of looking at things. This would also account for months where there is a 5th week
DECLARE #date VARCHAR(10)
SET #date = '7/27/2019'
SELECT CEILING(DATEPART(WEEK,#date)-((DATEPART(MONTH,#date)-1)*4.3333)) 'Week of Month'

Below will only work if you have every week of the month represented in the select list. Else the rank function will not work, but it is a good solution.
SELECT DENSE_RANK() OVER (PARTITION BY MONTH(DATEFIELD)
ORDER BY DATEPART(WEEK,DATEFIELD) ASC) AS WeekofMont

try this one
declare #date datetime = '20210928'
select convert(int,(((cast(datepart(day,#date) as decimal(4,2))/7)-(1.00/7.00))+1.00))

select datepart(week,#date)-datepart(week,dateadd(day,1,eomonth(dateadd(m,-1,#date))))+1
or
select datepart(week,#date)-datepart(week,dateadd(d,-datepart(d,#date)+1,#date))+1
steps:
1,get the first day of month
2,week of year of the date - week of year of the first day of the month
3,+1
2023-1-1 is sunday
SET DATEFIRST 1;
DECLARE #date date = '2023-1-02';
select datepart(week,#date)-datepart(week,dateadd(day,1,eomonth(dateadd(m,-1,#date))))+1
return 2
SET DATEFIRST 7;
DECLARE #date date = '2023-1-02';
select datepart(week,#date)-datepart(week,dateadd(day,1,eomonth(dateadd(m,-1,#date))))+1
return 1

Code is below:
set datefirst 7
declare #dt datetime='29/04/2016 00:00:00'
select (day(#dt)+datepart(WEEKDAY,dateadd(d,-day(#dt),#dt+1)))/7

select #DateCreated, DATEDIFF(WEEK, #DateCreated, GETDATE())

Related

Calculating week number SQL Server

I have a query where I need to calculate the week number based on the fiscal start of the year occurring on 01.07.YEAR
The problem I have is that when it goes to 30 Days of a calendar year I don't get the correct result and so I need to amend my script. I want a query that returns the correct week number regardless of what month I am in.
I have a calendar table populated; I add 18 months to the current date which give me the period and so I tried to do the same to the week but I am going around in circles.
Below is the code I am using:
SET DATEFIRST 1;
SELECT
[date],
DATEPART(wk, DATEADD(MONTH, 18, DATEADD(dd, -2, [date]))) 'FWeek',
LEFT(CONVERT(varchar, DATEADD(MONTH, 18, [date]), 112), 6) AS 'Period',
DATENAME(dw, [date]) AS 'Day'
FROM [dbo].[DP_PERIOD_DATES]
WHERE [date] >= '01/11/2018'
AND [date] < '04-01-2019'
ORDER BY [date] DESC
Try datediff to get the number of weeks from 1/7/x.
The extra datediff is to get the first of the year and add 6 to get the 7th of the year.
SELECT [date],
DateDiff(wk,
--JANUARY 7th of Current Year
DATEADD(yy, DATEDIFF(yy, 0, DATEADD(m,18,[date])), 0)+6
, DATEADD(m,18,[date]))
FROM [dbo].[DP_PERIOD_DATES]
WHERE [date] >= '01/11/2018'
AND [date] < '04-01-2019'
ORDER BY [date] DESC
SET FWEEK = DATENAME(yy, (DATEADD(month, 18, [date]))) + RIGHT('00'+DATENAME(dy,(datepart(DAYOFYEAR,DATEDIFF(DY,0,[date])/7*7+547)+5)/7),2)
, period = LEFT(CONVERT(varchar, DATEADD(month, 18, [date]),112),6)
Thanks Paul for all your help; it really wasnt easy as trying to apply someone elses logic to a date. I got it working using the above code in case anyone is looking for the same type of answer in the future

Get weeks in a month using SQL Server 2008

This year, August contains week #'s 31, 32, 33 & 34.
How can I make a query that gets all returns from each week in the month(8)?
Example:
select sum(a) as MyTot
from MyTable
where week numbers are included in month
Clear as mud?
I can get the return for each week because there is a field with the week number in it. I need to sum all the weeks that are in any given month.
Thanks,
You could create a calendar table, containing all kinds of data about dates - weekday, week number, day of year, day of month, month name, month number etc'. Then you can join your current table with the calendar table, filtering by the relevant month.
In fact, this might be a very useful thing to have, as pointed out by Aaron Bertrand in his Creating a date dimension or calendar table in SQL Server article.
Another option is to compute the first and last date of the month, get the week number of these dates, and use that to select the data from your table:
DECLARE #StartDate date = DATEADD(Month, DATEDIFF(Month, 0, GetDate()), 0)
DECLARE #EndDate date = DATEADD(Day, -1, DATEADD(Month, 1, #StartDate))
SELECT SUM(a) as MyTot
FROM MyTable
WHERE weekNumber >= DATEPART(WEEK, #StartDate)
AND weekNumber <= DATEPART(WEEK, #EndDate)
Please note, however, that the DATEPART(WEEK, #Date) return value depends on the value set by SET DATEFIRST. You might also want to look at ISO_WEEK.

Get sunday date between two date and last day from one month mysql

I want to get all sunday date between two dates and get last day between two date, how can i do that in mysql?
Example :
start date | end date
2017-03-01 | 2017-03-31
then the results are :
2017-03-05
2017-03-12
2017-03-19
2017-03-26
2017-03-31
Start date and end date possible to change, please advise me.
Thank you
Since you now mentioned that you don't have a table for the dates, you could approach it like this if you don't want to add a generic calendar table on your database.
declare #startdate datetime
declare #enddate datetime
DECLARE #startdateLoop datetime
select #startdate = CAST(start as DATE), #enddate = CAST(end_date as DATE) from #t
set #startdateLoop = #startdate
CREATE TABLE #tempCal
(dates datetime)
WHILE #startdateLoop != #enddate
BEGIN
INSERT INTO #tempCal
SELECT #startdateLoop
SET #startdateLoop = DATEADD(dd, 1, #startdateLoop)
END
SELECT * FROM #tempCal
WHERE dates between #startdate and #enddate and DAYOFWEEK(dates) = 1
You may turn this into a procedure if you want to.
Would still be nice if you DO HAVE a calendar table; as Tim has suggested.
MySQL has a DAYOFWEEK() function which would return 1 for any date which is a Sunday:
SELECT date_column
FROM yourTable
WHERE (date_column BETWEEN '2017-03-01' AND '2017-03-31' AND
DAYOFWEEK(date_column) = 1) OR -- any Sunday
date_column = '2017-03-31' -- or the last date in the range
I am assuming that yourTable already has dates in it. If you need help with populating a table with a range of dates, this problem has been covered well before on Stack Overflow, q.v. here:
How to populate a table with a range of dates?
Demo here:
Rextester
SELECT calender FROM calender WHERE calender.calender >='2017-03-01' AND calender.calender <='2017-03-31' AND DAYOFWEEK(calender) = 1 OR calender = '2017-03-31' Group By calender
This is #Tim Answer
Thanks Tim

MySQL: need to calculate the last Friday of a month

I'm trying to solve a task: I have a table containing information about ships' battles. Battle is made of name and date. The problem is to get the last friday of the month when the battle occurred.
WITH num(n) AS(
SELECT 0
UNION ALL
SELECT n+1 FROM num
WHERE n < 31),
dat AS (
SELECT DATEADD(dd, n, CAST(battles.date AS DATE)) AS day,
dateadd(dd, 0, cast(battles.date as date)) as fight,
name FROM num,battles)
SELECT name, fight, max(day) FROM dat WHERE DATENAME(dw, day) = 'friday'
I thought there must be a maximum of date or something, but my code is wrong.
The result should look like this:
Please, help!!
P.S. DATE_FORMAT is not available
Possible problem: as spencer7593 noticed - and as I should have done and didn't - your original query is not MySQL at all. If you're porting a query that's OK. Otherwise this answer will not be helpful, as it makes use of MySQL functions.
The day you want is number 4 (0 being Sunday in MySQL).
So you want the last day of the month if the last day of the month is a 4; if the day of the month is a 5 you want a date which is 1 day earlier; if the day of the month is a 3 you want a date which is 1 day later, but that's impossible (the month ends), so you really need a date six days earlier.
This means that if the daynumber difference is negative, you want it modulo seven.
You can then build this expression (#DATE is your date; I use a fake date for testing)
SET #DATE='2015-02-18';
DATE_SUB(LAST_DAY(#DATE), INTERVAL ((WEEKDAY(LAST_DAY(#DATE))+7-4))%7 DAY);
It takes the last day of the month (LASTDAY(#DATE)), then it computes its weekday, getting a number from 0 to 6. Adds seven to ensure positivity after subtracting; then subtract the desired daynumber, in this case 4 for Friday.
The result, modulo seven, is the difference (always positive) from the last day's daynumber to the wanted daynumber. Since DATE_SUB(date, 0) returns the argument date, we needn't use IF.
SET #DATE='1962-10-20';
SELECT DATE_SUB(LAST_DAY(#DATE), INTERVAL ((WEEKDAY(LAST_DAY(#DATE))+7-4))%7 DAY) AS friday;
+------------+
| friday |
+------------+
| 1962-10-26 |
+------------+
Your query then would become something like:
SELECT `name`, `date`,
DATE_SUB(LAST_DAY(`date`),
INTERVAL ((WEEKDAY(LAST_DAY(`date`))+7-4))%7 DAY) AS friday
FROM battles;

How to calculate a third monday of every month using SQL statement?

i need to trigger a notification. this notification has to be triggered every third monday of every month.
SELECT
(
DAYOFWEEK(NOW()) = 2
AND
DAYOFMONTH(NOW()) BETWEEN 15 AND 21
)
AS send_notice_today;
Try using dayofweek and dayofmonth functions. http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_dayofweek
Somehow you can check how many weeks are there from 1st of month to curdate() with dayofmonth (using an operation mod 7), and dayofweek should be 5 (thursday)
So perhaps MORE GENERALLY if you can get the "week of month" for the date using this:
(FLOOR((DAYOFMONTH(given) - 1) / 7)) AS 'week_of_month'
which I believe provides an accurate 0 based week-of-month index for a given date. then you can use the value to find any nth as in:
WHERE (week_of_month) = n AND weekday = {weekday}
you can also use the above to get the "last {weekday}" by:
WHERE (week_of_month >= 4) and weekday = {weekday}
note that the week_of_month can range from 0 to 5 (e.g., a 31 day month whose 1st falls on Saturday will have the 31st in the 6th week (5 as a 0 based index)
hope this helps ...
OK a bit more ... you might define the above as a function as in:
CREATE FUNCTION WEEKOFMONTH(given date) RETURNS int DETERMINISTIC RETURN (FLOOR((DAYOFMONTH(given) - 1) / 7))
and add another function:
CREATE FUNCTION WEEKNAME(given date) RETURNS text CHARACTER SET utf8 COLLATE utf8_unicode_ci DETERMINISTIC RETURN (CONCAT(ELT(WEEKOFMONTH(given)+1,'1st ','2nd ','3rd ','4th/Last ','5th/Last '),DAYNAME(given)))
then you can simply say things like
SELECT * FROM dataTable WHERE WEEKNAME(your_date_field) = "3rd Wednesday"
... I struggled with how the 4th/5th should be returned from WEEKDAY and settled on adding "/Last" for both under the theory that this is "good enough" should one want to test for either 4th, 5th or Last. Using this you can do:
SELECT * FROM dataTable WHERE WEEKNAME(your_date_field) LIKE "%Last%"
The date of the third monday of the current month would be given by the SQL statement:
SELECT date_add(date_sub(curdate(),INTERVAL dayofmonth(curdate())-1 DAY),
INTERVAL (7-weekday(date_sub(curdate(),INTERVAL dayofmonth(curdate())-1 DAY)))+14 DAY)
The approach that I'm taking is get the 1st Monday of the month, and depending on when in the month it is, add either 2 or 3 weeks to it (since when it falls out before/on Monday, you only need to walk 2 more weeks):
;with
filler as (select row_number() over (order by a) a from (select top 100 1 as a from syscolumns) a cross join (select top 100 1 as b from syscolumns) b),
dates as (select dateadd(month, a-1, '1/1/1900') date from filler where a <= 2000),
FirstMonday as (
select dateadd(day, case datepart(weekday,Date)
when 1 then 1
when 2 then 0
when 3 then 6
when 4 then 5
when 5 then 4
when 6 then 3
when 7 then 2
end, Date) as Date
,case when datepart(weekday,Date) = 1 then 3 else 2 end as Weeks
from dates
)
select dateadd(week, Weeks, Date) as ThirdMonday
from FirstMonday
This one calculates the first Monday of any month given the year-month-day
SET #firstday = '2015-04-01';
SELECT ADDDATE( #firstday , MOD((9-DAYOFWEEK(#firstday)),7)) as first_monday;
This one calculates the third Monday of any month given the year-month-day
SET #firstday = '2015-01-01';
SELECT ADDDATE( #firstday , MOD((23-DAYOFWEEK(#firstday)),21)) as third_monday;
This one calculates the third Friday of any month given the year-month-day
SET #firstday = '2015-09-01';
SELECT ADDDATE( #firstday , MOD((20-DAYOFWEEK(#firstday)),20)) as third_friday;
Thanks to #Brewal for the original question and #User2208436 for pointing us toward the answer.
Here's an answer that does not use DAYOFWEEK or DAYOFMONTH. It uses DATEADD and DATEPART only.
We'll need two helper functions:
CREATE FUNCTION dbo.day_of_week(#date Date)
RETURNS INT
AS BEGIN
-- (1 for Sunday, 2 for Monday, etc)
RETURN DATEPART(dw, DATEADD(year, year(#date)-1900, DATEADD(month, month(#date)-1, DATEADD(day, day(#date)-1, 0))))
END
GO
CREATE FUNCTION dbo.date_from_parts(#year INT, #month INT, #day INT)
RETURNS DATE
AS BEGIN
RETURN DATEADD(year, #year-1900, DATEADD(month, #month-1, DATEADD(day, #day-1, 0)))
END
GO
Then using the following example data:
DECLARE #day_of_week INT
SET #day_of_week = 2 -- Monday
DECLARE #year INT
DECLARE #month INT
SET #year = 2016
SET #month = 11
Let's first obtain the FIRST Monday of the month:
We will add an offset, (day_of_week - day of week of first day of the month) % 7, to the first day of the month.
(Also notice we need the construction ((x % n) + n) % n instead of just x % 7, to keep the answer within 0 and 6. For example, just SELECT -3 % 7 returns -3! See Mod negative numbers in SQL just like excel)
Now here's the final construction to obtain the first Monday of the month:
SELECT
DATEADD(
dd,
(((#day_of_week -
dbo.day_of_week(dbo.date_from_parts(#year, #month, 1))) % 7) + 7) % 7,
dbo.date_from_parts(#year, #month, 1)
)
To obtain the third Monday of the month, add 14 to the second term of this answer.
If #firstday is the first day of the month
select date_add(#firstday,
interval (if(weekday(#firstday)>0,21-weekday(#firstday),14)) day);
yields the 3rd monday of the month.
Tested with all months of 2018.
Seems simpler than previous solutions.
The key is the if function on weekday.
if weekday = 0 (first day is a monday), add 14 days
if weekday > 0, add 21 days and subtract the weekday
DECLARE #YEAR DATE='2019-01-01'
SELECT DATEADD( d, 23-(DATEPART(dw,#YEAR )%21),#YEAR )
This will help to get the third Monday of whatever month you want.