Week of the year for weeks starting with Saturday - mysql

We have customers that currently have defined weeks starting either on Sat, Sun or Monday. Came across these DATE_FORMAT options which nicely handle the week starting on Sunday and Monday but can't find a way to do same for week starting on Saturday. Any suggestions?
%U Week (00..53), where Sunday is the first day of the week
%u Week (00..53), where Monday is the first day of the week

I had a similar issue: I needed to calculate week numbers based on the following rules:
Week starts on Friday
The remainder days of an year (all the days after the last Friday of the year that do not complete a week) should be counted in the
first week of the next year.
For example:
27/12/2012 (Thursday) should be Week 52 of 2012
28/12/2012 (Friday) should be Week 1 of 2013
Week 1 2013 goes from 28/12/2012 to 3/1/2013
I made this statement that calculates both the YEAR and WEEKNUMBER based on these rules that you can easily adapt to your circunstance:
SELECT IF(ceil(( dayofyear(current_date) + dayofweek(date_format(current_date, '%Y-01-01'))+1 )/7) > 52, YEAR(current_date)+1, YEAR(current_date)),
IF(ceil(( dayofyear(current_date) + dayofweek(date_format(current_date, '%Y-01-01'))+1 )/7) > 52, 1, ceil(( dayofyear(current_date) + dayofweek(date_format(current_date, '%Y-01-01'))+1 )/7));
The tricky part is just this expression:
ceil(( dayofyear(current_date) + dayofweek(date_format(current_date, '%Y-01-01'))+1 )/7)
The rest (If clauses) are just for adapting the result of the expression to make year+1 and week = 1 on week 53.
I'll try to explain the expression as best as I can. The following expression gives you the week number pure simple (the day of the year divided by 7 days in a week rounded up):
ceil(( dayofyear(current_date))/7)
But now you want to make it start on Friday (or any other day). To do this you need to add to the current day, the days of the first week that were part of the previous year (it's like your current actually started a few days before, because your first week contains days from the previous year).
This expression calculates that offset based on the weekday on Jan/1:
dayofweek(date_format(current_date, '%Y-01-01'))+OFFSET
The offset is the difference between 7 and the weekdaynumber you want the week to start:
0 for Saturday
1 for Friday
2 for Thursday
3 for Wednesday
...
So now you just have to add it to the previous one resulting in the above mentioned expression that calculates the week numbers starting on any weekday and assuming week 1 to start on the previous year:
ceil(( dayofyear(current_date) + dayofweek(date_format(current_date, '%Y-01-01'))+OFFSET )/7)
Then I just added an IF that turns week 53 into week 1 and another to add 1 to the year if it's week 53.

It took me a while to think on this question.
ISO standard defines the first week to start on Monday and contain 4th day of the year.
MySQL's functions provide much more choices.
date_format() flags %U and %u are using notation where first week is the one where Sunday or Monday is first met. As this is not according to the ISO, I will provide both variants.
If you want to count week numbers starting from Saturday and first year's week is the one containing Saturday, you can use one of the following expressions:
SELECT sign(dayofweek(current_date) - 7) + ceil(dayofyear(current_date)/7);
SELECT ceil((dayofyear(current_date)+
(dayofweek(date_format(current_date, '%Y-01-01'))%7-7))/7);
If first year's week is the one where 4th day of the year falls into, use:
SELECT ceil((dayofyear(current_date)+
(dayofweek(date_format(current_date, '%Y-01-04'))%7-4+1))/7);
The very first expression is quite straightforward.
I will elaborate on the 2nd and 3rd ones. I calculate week number by taking current day of the year, dividing by 7 and ceiling up, quite simple. Week number needs to be adjusted based on the situation at the beginning of the year though.
for the first case (first week starts with the first Saturday), I take day-of-week for the Jan/1 of the year in subject, make Saturday as the day 0 and then adjust day-of-year by the difference. This this makes all days before first saturday yielding negative adjustment number and it ceils up to zero;
for the second case (first week is the one where 4 day of the year falls in), I take day-of-week for the Jan/4 of the year in subject, make Saturday as the day 0. The -4+1 formula gives adjustment to the first Saturday before Jan/4, +1 is used as days of the year starts from 1, not from 0. Negative adjustment means 1st day of the year is not in the first week of the year.
Here're some test dates on the SQL Fiddle.
If you want to count weeks from any other day, you just have to change the formula, making that day being 0 in the sequence. Say, to count weeks starting from Wednesday, use:
SELECT ceil((dayofyear(current_date)+
((dayofweek(date_format(current_date, '%Y-01-04'))+3)%7-4+1))/7);
+3 is used as it complements dayofweek() value for Wednesday to the 7.

Make an adjustment based on DAYOFWEEK().

Related

Is there any function in sql to extract week?

I want to extract week from datetime, the output I want is 'YY/week', where week is the week of the year (eg '201724' is the 24th week in 2017).
The term "week of the year" is too ambiguous.
The week may start from Sunday, Monday or another weekday
The weeks enumeration in the year may start from 0 or 1
The weeks enumeration in the year may start from the week which includes January, 1 (and hence may be partial) or from first complete week of the year
The last week of the year, if it is partial, may be counted or not
Each DBMS has its own functions (sometimes original, always with original names) that can return the number of the week in the year on a given date. But they can not always take into account the above features.
Important addition provided by jarlh:
ISO 8601 (#4.3.4):
The first calendar week of a year is the one that includes the first Thursday of that year.
The last calendar week of a calendar year is the week immediately preceding the first calendar week of the next calendar year.
Week 1 is the first week of a year.
A calendar week starts on a Monday.
ISO 9075 doesn't even mention weeks.
SELECT TO_CHAR(TO_DATE('19-FEB-22') , 'IW') from DUAL;
To get the corresponding four-digit year, use
SELECT TO_CHAR(TO_DATE('19-FEB-22'), 'IYYY') FROM DUAL;
TO_CHAR() having so many options like this read more in Oracle manual or extract portation of date Extract Portion of Date Time Value
OutPut
You can use the following Mysql type query to extract.
SELECT DATE_FORMAT(BirthDate, " %u %Y") FROM Employees;
where the BirthDate date column in the database and the Employees is the table name.
This will result
49 1968
08 1952
35 1963
Week and the year.
in postgresql:
SELECT to_char('2016-12-31 13:30:15'::timestamp without time zone, 'yy/ww') ;
result:
16/53

I m try to get the weeknum for a week starting on Thursday with the input given as date

Select week('2017-08-03')
it gives me 31 as week number but it should be 32.
By googling I tried
select week('2017-08-03',4)
still I only get 31.
Here based on the input date given i'm trying to get the week number considering week starts on Thursday and end on Wednesday.
Any help in this is much appreciated
Thanks
From the documentation, the mode argument to WEEK specifies whether the week starts on Sunday or Monday, and how weeks are counted. There's no option to start on Thursday. Here are the meanings of each value:
So 4 means that the week starts on Sunday, week numbers start at 0, and week 1 is the first week with 4 or more days in the year.
See MySQL query yearweek of the current week to start on a Thursday, end on Wednesday for how to do what you want.

How to get first week of the every month ends with Thursday in SSRS?

i have a difficult requirement that i need to show the first week of the every month should end with Thursday and second week start with Friday and ends with Thursday,
for example may first week should be 05/01/2016 - 05/05/2016 and
second week 05/06/2016 - 05/12/2016 and third week 05/13/2016 - 05/19/2016 and fourth week 05/20/2016 - 05/26/2016 and fifth week 05/27/2016 - 05/31/2016.
example: when i select the March value in Month parameter it has to show like below image.
enter image description here
and i am building this report on CUBE data source, i need to do it in MDX

MySQL compare by week

I have a select statement of which needs to base its WHERE on a timestamp but for all dates within that week beginning monday.
The MySQL
SELECT DISTINCT(unique_reference) AS unique_reference, date(datetime) AS datetime
FROM sales_tickets
WHERE Date(datetime)='$datetime'
This is based on the fact that $datetime can be any date but the select statement needs to get all records from that week, example: if its the Monday 12th May 2014, it will fetch all results from that week, instead of the one day.
Currently, its fetching only one day of results.
I have no idea how to rectify this issue. Any advise would be awesome thanks.
You can compare using the WEEK function :
WHERE WEEK(DATE(datetime)) = WEEK('$datetime')
If you have multiples years for entries, you can use instead the YEARWEEK function.
Edit for first day of week:
WEEK and YEARWEEK functions have both a second optional argument which tells when a week start. Try to consider mode 1 or 5.
Mode First day of week Range Week 1 is the first week …
0 Sunday 0-53 with a Sunday in this year
1 Monday 0-53 with 4 or more days this year
2 Sunday 1-53 with a Sunday in this year
3 Monday 1-53 with 4 or more days this year
4 Sunday 0-53 with 4 or more days this year
5 Monday 0-53 with a Monday in this year
6 Sunday 1-53 with 4 or more days this year
7 Monday 1-53 with a Monday in this year
A sargable solution would explicitly calculate the start and end points of your desired range:
WHERE datetime >= DATE('$datetime') + INTERVAL 0 - WEEKDAY('$datetime') DAY
AND datetime < DATE('$datetime') + INTERVAL 7 - WEEKDAY('$datetime') DAY
The easiest method might be to have your WHERE statement check against a range of values, which you can calculate beforehand.
I'll assume you're using php.
So your SQL statement will be:
SELECT DISTINCT(unique_reference) AS unique_reference, date(datetime) AS datetime
FROM sales_tickets
WHERE (Date(datetime) > '$startDate')
AND (Date(datetime) < '$endDate');
You'll first have to figure out what $startDate and $endDate are:
$endDate = strtotime('Monday', time()); // might need to adjust this depending on when your week starts
$startDate = $endDate - 7*24*60*60; //one week before.
Be careful with converting times between unix timestamps and datetimes used in SQL, but you get the idea.
Try WEEK():
WHERE WEEK(datetime)=WEEK('$datetime')
Read more: WEEK()

How To Get YEARWEEK() To See Sunday As The Start Of The Week?

I'm trying to get the YEARWEEK function to see Sunday as the 1st day of the week.
An example date is: Sunday 1st Mar 2009
Here is my sql
SELECT YEARWEEK('2009-03-01')
and the result is
-> 200909
Which is week 9. I believe it is telling me this is week 9 because it sees the sunday as the last day of the previous week.
How would I get this function to see sunday as the 1st day of the week and therefore return as week 10?
According to http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_yearweek, YEARWEEK has an optional second argument which controls this. YEARWEEK('2009-03-01', 0) should do what you want (but see the table of possible values under WEEK on that page).
this will do it:
SELECT YEARWEEK('2009-03-01')+IF(WEEKDAY('2009-03-01')=6,1,0);
EDIT: this is the better solution, for more information click here:
SELECT YEARWEEK('2009-03-01',0);
(but i don't know why you want to do this - 2009.03.01 is in week 9, not 10...)