SQL Code to get Week Number when week begins Sunday to Saturday - mysql

My company’s week begins on a Sunday.
The issue I’m having is extracting the week number from the date in the database.
For example,02/01/2022 falls in week 52 of 2021 using the Sunday week beginning logic. How can I write a SQL code to give me :
a) the week number (I.e 2nd Jan 2022 is part of week 52)
b) the correct year of the week. i.e 2nd Jan 2022 , I want it to bring back the year “2021” so my data set is complete and accurate.
N.b.
Database name I’m using is dw-fin and column of the date is called date-created

You can use the WEEK function with a 'mode'.
Which is an integer indicating the starting of the week.
And the YEARWEEK function also has a mode.
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
Example :
select date_column
, month(date_column) as month
, year(date_column) as year
, yearweek(date_column, 2) as mode2_yearweek
, floor(yearweek(date_column, 2)/100) as mode2_year
, week(date_column, 2) as mode2_week
from (select date('2022-01-01') as date_column) q;
date_column
month
year
mode2_yearweek
mode2_year
mode2_week
2022-01-01
1
2022
202152
2021
52
Demo on db<>fiddle here

Related

Group by weekofyear MySQL for the end of the year

I need stats on orders, week by week, so I have done this:
SELECT YEAR(orders.date), WEEKOFYEAR(orders.date), COUNT(*)
FROM orders
GROUP BY YEAR(orders.date), WEEKOFYEAR(orders.date)
It worked for one year, but just now (new year) it does not count the last days of 53rd week (jan 1st, 2nd, 3rd). How can I update my Query in order to have the full last week (from Monday 2015-12-28 to Sunday 2016-01-03)?
You need to switch to YEARWEEK(orders.date,3) to get the ISO weeks as a single column. Using WEEK(orders.date,3) (which is exactly the same as WEEKOFYEAR) will return the correct week number, but YEAR(orders.date) will return either 2015 or 2016, splitting the week into four days in 2015 and and three days in 2016.
As Strawberry mentioned in the comments you're looking for the WEEK function. I just checked the documentation at the MySQL website.
Week(date [,mode])
This function returns the week number for date. The two-argument form of WEEK() enables you to specify whether the week starts on Sunday or Monday and whether the return value should be in the range from 0 to 53 or from 1 to 53. If the mode argument is omitted, the value of the default_week_format system variable is used
Here's an example
SELECT WEEK('2008-12-31',1);
=> 53
It should also be noted that this is not the same as the WEEKOFYEAR function.
Returns the calendar week of the date as a number in the range from 1 to 53. WEEKOFYEAR() is a compatibility function that is equivalent to WEEK(date,3).
We can see that the value of the mode parameter here is 3. Here is the table that shows the values for the modes
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 a Sunday in this year
5 Monday 0-53 With 4 or more days this year
6 Sunday 1-53 With a Sunday in this year
7 Monday 1-53 With 4 or more days this year
Source
https://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_week
As I understand you, you want calculate total orders for one week only once not twice for various years.
I've written SQL query for SQL Server, but I think you can easy rewrite it on mysql.
DECLARE #test_table TABLE(created_date DATETIME, VALUE INT)
INSERT INTO #test_table
SELECT N'20151231', 10
UNION ALL
SELECT N'20151228', 20
UNION ALL
SELECT N'20160101', 40
UNION ALL
SELECT N'20160104', 5
UNION ALL
SELECT N'20160107', 2
SELECT first_day_week_number,
SUM(value) AS total
FROM
(SELECT *,
DATEPART(ww,
DATEADD(dd, -DATEPART(dw, created_date)+2, created_date)) AS first_day_week_number
FROM #test_table ) AS T
GROUP BY first_day_week_number
To avoid problems with years you could calculate first week day of order date and then get week number from it.

week number returns previous year last week number for january fist week in mysql

I am facing one issue while fetching the week number for 2016-01-01(fist week) in mysql. it return 53 if i use week() function or weekofyear() function . I have to get as 1 since I am linking the weeknumber in my project in other places and if it returns 1 the next week number also should be adjusted according to that. Kindly any one help me on this.
The manual says:
If the week containing January 1 has 4 or more days in the new year,
it is week 1.
Otherwise, it is the last week of the previous year, and the next week
is week 1.
So you can provide the mode to the week function.
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
Something like this:
select WEEK('2016-01-01',0) + 1;
FIDDLE DEMO

mysql query to exclude sunday from two dates

If complaint filed on 5 pm on Saturday and closed on 1 pm on Monday, ticket should exclude sunday 24 hours.
Complaint Creation Date:24 Sept 2014, 6:00 PM Sat
Complaint Closed Date : 26 Sept 2014 ,6:00 PM Monday
Time taken :1 day not 2 day
Need Suggestions..
You can try somthing like this:-
SELECT CASE WHEN DAYNAME(DATE_ADD(Complaint_Creation_Date, INTERVAL 1 day)) = 'Sunday'
THEN (TIMESTAMPDIFF(HOUR,Complaint_Creation_Date,Complaint_Closed_Date))/24 - 1 AS "TIME TAKEN"
ELSE
(TIMESTAMPDIFF(HOUR,Complaint_Creation_Date,Complaint_Closed_Date))/24 AS "TIME TAKEN"
END
FROM YOUR_TABLE;

MySQL get next day & time combination

Using MySQL, how do I find the next weekday/time combination after a given datetime?
For example, how do I select the next Sunday at 10AM given an input date of Tuesday 12 August 2014 6PM - which should return: Sunday 17 August 10AM?
SELECT DATE_ADD(#input_date, INTERVAL (8 - DAYOFWEEK(#input_date)) DAY) AS next_sunday
From: http://www.gizmola.com/blog/archives/99-finding-next-monday-using-mysql-dates.html
SELECT DATE_ADD('2014-08-12', INTERVAL 5 DAY) as NEXTSUNDAY;

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()