mysql Same day every year - mysql

I need to use September 1st in a where clause and don't want to hard code the year. Whats the best way to return 9/1/year to use in a between statement?
where p.post_date between '2016-09-01' and DATE_ADD(CURDATE(),INTERVAL 1 DAY)
Looking for a replacement of the '2016-09-01' so that it works again next year and going forward. Also, needs to work for oct, nov and dec, of same year.

You can use month() and day():
select t.*
from t
where month(datecol) = 9 and day(datecol) = 1;

I guess you want get the year/09/01 of current year?
SELECT *
FROM YourTable
WHERE datecol = CONCAT ( YEAR(CURDATE()) , '/09/01')

Basically, you want the previous year when you are before the turning date in the current year and the current one when you are after the turning date.
I would suggest to tell MySQL what date format you are using, to do so, you can use the STR_TO_DATE function.
CASE
WHEN MONTH(CURDATE()) < 9 THEN STR_TO_DATE(CONCAT(YEAR(CURDATE())-1, '-09-01'), '%Y-%m-%d')
ELSE STR_TO_DATE(CONCAT(YEAR(CURDATE()), '-09-01', '%Y-%m-%d'))
END
You can put this in a function/routine and use it wherever you need.

Related

DATE_FORMAT two times in Where Clause doesn't work

I want to check if a dataset is older than the current month -1 day (so if it's the first of November it should still be older than October). This is my SQL:
SELECT *
FROM XY
WHERE DATE_FORMAT(calendar_day, '%Y-%m') <> DATE_FORMAT((CURRENT_DATE()-1, '%Y-%m');
But it doesn't work because of the second DATE_FORMAT. If I remove it, it works, but then it also compares the days and not the months. How do I solve this?
I want to check if a dataset is older than the current month -1
Don't use DATE_FORMAT() on a column for this type of query. Keep all date functions on the "current date". Functions on columns impede optimization.
I think this does what you want:
SELECT *
FROM XY
WHERE calendar_day <= LAST_DAY(CURRENT_DATE() - interval 1 day - interval 1 month);
Try this using year and month function:
SELECT *
FROM XY
WHERE (year(calendar_day) <> year(CURRENT_DATE()-1))
and (month(calendar_day)<>month(CURRENT_DATE()-1))

Is it possible to loop in MySQL for sales data?

I am trying to build a useful query for our sales team to see how many sales our business has made in the current month, compared to the same point in the previous months.
So if today is the 14th of September, I want to compare how many sales we'd made between 1st - 14th of August and so on to see if we are up or down.
I have created the query to pull the data, but it's not in any kind of loop. Can anyone suggest a way to do this please? Below shows me the data for July 2015...
SELECT CONCAT(MONTH(OrderDate),'-',YEAR(OrderDate)) AS MontyYear,
COUNT(sw_orders.OrderNumber) OrderCount,
SUM(Gross) GrossIncome
FROM
orders
WHERE
orders.MasterOrderNumber = ''
AND Date(OrderDate) >= '2015-07-01'
AND Date(OrderDate) <= Concat('2015-07-', DAY(CURDATE()))
order by orders.ordernumber;
It feels like I need a variable that is the month number, so starts at "1" for January - then counts up per loop and use is used in the OrderDate part of the query?
I would not use string literals in the query, but make use of MySql's DAY and MONTH function:
WHERE orders.MasterOrderNumber = ''
AND DAY(OrderDate) <= DAY(CURDATE())
GROUP BY MONTH(OrderDate)

SQL - Get result of current year only

How can I get the result of the current year using SQL?
I have a table that has a column date with the format yyyy-mm-dd.
Now, I want to do select query that only returns the current year result.
The pseudo code should be like:
select * from table where date is (current year dates)
The result should be as following:
id date
2 2015-01-01
3 2015-02-01
9 2015-01-01
6 2015-02-01
How can I do this?
Use YEAR() to get only the year of the dates you want to work with:
select * from table where YEAR(date) = YEAR(CURDATE())
Using WHERE YEAR(date) = YEAR(CURDATE()) is correct but it cannot use an index on column date if exists; if it doesn't exist it should.
A better solution is:
SELECT *
FROM tbl
WHERE `date` BETWEEN '2015-01-01' AND '2015-12-31'
The dates (first and last day of the year) need to be generated from the client code.
When I tried these answers on SQL server, I got an error saying curdate() was not a recognized function.
If you get the same error, using getdate() instead of curdate() should work!
--========= Get Current Year ===========
Select DATEPART(yyyy, GETDATE())
SELECT id, date FROM your_table WHERE YEAR( date ) = YEAR( CURDATE() )
SELECT
date
FROM
TABLE
WHERE
YEAR (date) = YEAR (CURDATE());
If the date field contains a time component, you want to include December 31 so you have to go to January 1 of the next year. You also don't have to use code to insert dates into the SQL. You can use the following
SELECT * FROM table
WHERE date BETWEEN MAKEDATE(YEAR(CURDATE()), 1) AND MAKEDATE(YEAR(CURDATE())+1, 1)
This will give you January 1st of the current year through January 1st at midnight of the following year.
As #Clockwork-Muse pointed out, if the date field does not contain a time component, you would want to exclude January 1 of the following year by using
WHERE date >= MAKEDATE(YEAR(CURDATE()), 1) AND date < MAKEDATE(YEAR(CURDATE())+1, 1)
You can do this using SQL DATE_FORMATE(). like below:
SELECT
date
FROM
TABLE
WHERE
DATE_FORMAT(date, '%Y') = YEAR (CURDATE());
SELECT [ID]
,[datefield]
FROM [targettable]
WHERE DATEPART(YYYY, [datefield]) = (SELECT TOP 1(MAX(DATEPART(YYYY, [datefield])))
FROM [targettable]
)
/*
This will find the newest records in the table regardless of how recent the last time data was entered.
To grab the oldest records from the table do this
SELECT [ID]
,[datefield]
FROM [targettable]
WHERE DATEPART(YYYY, [datefield]) = (SELECT TOP 1(MIN(DATEPART(YYYY, [datefield])))
FROM [targettable]
)
*/

Selecting 'DATE' fields in mysql by month and day with comparison

Trying to select a closest previous and next holiday from the database. Say, New Year's Day is always at the 1st of January, and New Year's Eve is at the 31st of December. Current year is completely irrelevant, so I'm trying to select previous holiday by day and month (New Year's Eve) with the following MySQL query:
SELECT * FROM `calendar` WHERE DATE_FORMAT(`holidayDate`, "%m-%d") < "01-01"
It gives NULL. I was expecting that it would drop through and will look in the previous month, December, but...
Tried a lot of different ways of doing it, but still no success.
P.S.: Cannot use TIMESTAMP in this case...
The reason it's returning null is because there isn't anything less than '01-01'. The query doesn't wrap around to the beginning.
What I would do is write a case statement that checks to see if you are at the earliest holiday.
If you are the earliest holiday, then you can select the latest holiday (a way of wrapping around).
If you are not the earliest holiday, then you need to select the one before it. I did this by ordering them in descending date, and limiting it to 1. (Effectively grabbing the holiday occurring before the current date.)
Try this:
SELECT *
FROM calendar
WHERE
CASE WHEN DATE_FORMAT(CURDATE(), '%m-%d') = DATE_FORMAT((SELECT MIN(c.holidayDate) FROM calendar c), '%m-%d')
THEN holidayDate = (SELECT MAX(c.holidayDate) FROM calendar c)
ELSE
DATE_FORMAT(holidayDate, '%m-%d') < DATE_FORMAT(CURDATE(), '%m-%d')
END
ORDER BY holidayDate DESC
LIMIT 1;
Here is an SQL Fiddle example. I created two queries. One that uses the current date (seen above) and one that has Jan 1st hard coded to show that the case statement does work. I've only added certain holidays to test.
If two queries are acceptable for you:
SELECT max(holidayDate) as prev_holiday from calendar where holidayDate < now();
SELECT min(holidayDate) as next_holiday from calendar where holidayDate > now();

Calculate difference between dates

The title might be a bit misleading, but what I want is:
SELECT * FROM table ORDER BY pid ASC
And in one of the columns I have a DATE(). I want to compare the current date (not time) and return how many days are left till that date. Let's say the date is 2013-04-20 and today's date is 2013-04-16 I don't want to get any data if it's < current date. If it is I want it returned in days.
I've been looking around here and I've found no way to do it, and I can't for the love of me figure it out.
If you're looking for the difference between two date you can use the GETDATE function in MS SQL
SELECT DATEDIFF(DD, DateOne, DateTwo) FROM TABLE
This will return the difference in number of days between the two dates.
If you only want rows where the date field is less than or equal to today's date you can use:
SELECT DATEDIFF(DD, DateField, GETDATE())
FROM TableName
WHERE DateField <= GETDATE()
If you're using MySQL you can use DATEDIFF()
SELECT
DATEDIFF(NOW(), date_column) AS days_diff
FROM
tablename
Get the difference between two dates (ANSI SQL)
select the_date_column - current_date as days_left
from the_table
where the_date_column - current_date <= 4;
SQLFiddle: http://sqlfiddle.com/#!12/3148d/1