MySQL compare by week - mysql

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

Related

MySQL How to get First Sunday and last Saturday of previous month using curdate()

I really need help with the correct way to get the first sunday of the previous month and the last Saturday of the previous date using curdate().
This is what I am using for the current month:
select date_add(curdate(),interval -DAY(curdate())+2 DAY)
select adddate(last_day(curdate()),-mod(weekday(adddate(last_day(curdate()),6)),2))
But I am looking for guidance on the correct SQL for the previous month. My goal is the get the last rolling 12 months data broken out by month over month but cannot get the between the first sunday and last saturday correct. Please help!!!

MySQL Select From Prior Week, not just 7 days

I am attempting to get a query that selects the week prior (Sun-Sat). I've fought with this query and the closest I can get is the last 7 days, using the following:
SELECT *
FROM dates
WHERE date BETWEEN CURDATE()-INTERVAL 1 WEEK AND CURDATE();
I'm really unsure how to proceed from here. It seems as if I need to create some kind of relation between CURDATE() and the Saturday before maybe?
Any help is appreciated.
You are after the Week of the year.
Look at the Week Function: WEEK(date[,mode])
http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_week
The mode describes how you define the week (which is the start of the week)
WEEK(date,3) is for a week that starts Monday.
SELECT *
FROM dates
WHERE
-- Last Week
WEEK(date,3) = WEEK(CURDATE(),3)-1
AND YEAR(date)= YEAR(CURDATE()) ;
Don't forget the year. Week is just a number between 1 and 52. So the Year is important!
The code above is not correct. it will fail on the last week of the year!

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.

Selecting mysql records for next week

I'm looking for the MySQL query to select date records that fall within the next week using Sunday - Saturday as the format for the week.
So in other words, I'm not looking to get the dates a week from today, I'm looking to get the dates that fall within Sunday - Saturday of the next week.
I found this: MySQL Query to select data from last week? and it works for the previous week from Sunday - Saturday but I'm not sure how to tweak this to get the dates for the next week.
Any ideas?
SELECT * FROM table
WHERE
date > date_add(curdate(),INTERVAL(7-dayofweek(curdate()))DAY)
AND date <= date_add(curdate(),INTERVAL(14- dayofweek(curdate()))DAY)
You can use:
SELECT *
FROM YourTable
WHERE WEEK(YourDateField, 6) = WEEK(CURRENT_DATE + INTERVAL 7 DAY, 6)
for selecting recods of next week (starting with sunday)
Weeks count is 1 to 53 with first week of the year having at least 4 days in the year

How to find the first Sunday of the month in MySQL?

I did not find any of examples for MySQL - all of them were quite complicated.
How can I SELECT the first Sunday of the month?
So choose the first day of the month: 2012-01-01 (or whatever month and year you want).
Get the weekday index of the date. Indexes here are from 0 to 6.
Subtract that index from 6 and you will get how many days you need to add until the date is Sunday.
Add that amount of days to the chosen day.
SELECT DATE_ADD("2012-01-01 10:00:00", INTERVAL (6 - WEEKDAY("2012-01-01 10:00:00")) DAY);
Or:
SELECT DATE_ADD("2012-01-01", INTERVAL (6 - WEEKDAY("2012-01-01")) DAY);
So choose the first day of the month: 2021-08-01 (or whatever month and year you want).
SELECT ADDDATE( '2021-08-01' , MOD((8-DAYOFWEEK('2021-08-01')),7))