I have this query where I provide to-date & from date.
SELECT *
FROM sales
WHERE date between to-date AND from-date;
Now I want to execute this query with following parameters
to-date = Oct-2015
some-other-date = Oct-2015
That is I want records of the whole month.
How would I do that in a query where I have to and from dates provided it will work for both scenarios where months can be same and different as well.
Update:
dataType for column date is date
You can find the first day of the month containing any given timestamp with an expression like this. For example by using the timestamp NOW(), this finds the first day of the present month.
(DATE(NOW() - INTERVAL DAYOFMONTH(DATE(NOW()))
That's handy, because then you can use an expression like
(DATE(NOW() - INTERVAL DAYOFMONTH(DATE(NOW())) - INTERVAL 1 MONTH
to find the beginning of the previous month if you like. All sorts of date arithmetic become available.
Therefore, you can use an expression like the following to find all records with item_date in the month before the present month.
WHERE item_date>=(DATE(NOW()-INTERVAL DAYOFMONTH(DATE(NOW()))- INTERVAL 1 MONTH
AND item_date < (DATE(NOW()-INTERVAL DAYOFMONTH(DATE(NOW()))
Notice that we cast the end of a range of time as an inequality (<) to the moment just after then end of the range of time.
You may find this writeup useful. http://www.plumislandmedia.net/mysql/sql-reporting-time-intervals/
It's often useful to create a stored function called TRUNC_MONTH() to perform the conversion of the arbitrary timestamp to the first day of the month. It makes your SQL statements easier to read.
select * from sales
where from-date >= 1-Oct-2015
and to-date <= 1-Nov-2015
Update
select * from sales
where date >= from-date
and date <= to-date
Here is SQLFIDDLE
You Can get month from your both to and from dates and find records of that month
SELECT * FROM sales
WHERE MONTH('2002-01-03') AND MONTH('2002-01-3')
SqlFiddle of Using Month Function
Related
I have two input fields
[start_date] - [end_date]
Whenever you type in a date range in YYYY-MM-DD, f.e: [2015-12-01] - [2015-12-05]
I want to make an SQL query to find out which invoices that is due in that period.
There is no column in the database that stores the duedate, only the invoice_date.
Due date is always invoice_date + 17days
Is there anyway to extract the relevant invoices from this?
This is my current query, but it only picks invoices thats has been generated in the range.
I want it to find those who are DUE in the above entered range.
select * from orders
inner join
order_invoice on order_invoice.id_order = orders.id_order
where (current_state = 14) and
orders.date_add >= "'.$start_date.'" and
orders.date_add <= "'.$end_date.'" and
now() >= DATE_ADD(order_invoice.date_add, INTERVAL 17 DAY)
Move your range ([start_date] and [end_date]) 17 days left (subtract from date params) and you will get range for date_add. No difference: to add 17 days to date_add or to subtract same value from both range bounds.And I actually don't understand what is now() function doing in filter predicate. Seems it does not correspond task described. May be you have to think up something for [end_date] for proper current date/future handling.
I have a MySQL DB table with multiple date type fields. I need to do different SELECT queries on this table but I am not sure which way is the best to find records from the same month.
I know I can do the following:
SELECT *
FROM table
WHERE MONTH(somedate) = 5
AND YEAR(somedate) = 2015
But I keep reading that isn't efficient and that I should go with using actual dates, i.e.
SELECT *
FROM table
WHERE somedate BETWEEN '2015-05-01' AND '2015-05-31'
However, all I would have is the month and the year as variables coming in from PHP. How do I easily and quickly calculate the last day of the month if I go with second option?
Don't calculate the last day of the month. Calculate the first day of the next month instead.
Your query can be like this
WHERE t.mydatetimecol >= '2015-05-01'
AND t.mydatetimecol < '2015-05-01' + INTERVAL 1 MONTH
Note that we're doing a less than comparison, not a "less than or equal to"... this is very convenient for comparing TIMESTAMP and DATETIME columns, which can include a time portion.
Note that a BETWEEN comparison is a "less than or equal to". To get a comparison equivalent to the query above, we'd need to do
WHERE t.mydatetimecol
BETWEEN '2015-05-01' AND '2015-05-01' + INTERVAL 1 MONTH + INTERVAL -1 SECOND
(This assumes that the resolution of DATETIME and TIMESTAMP is down to a second. In other databases, such as SQL Server, the resolution is finer than a second, so there we'd have the potential of missing a row with value of '2015-05-31 23:59:59.997'. We don't have a problem like that with the less than the first day of the next month comparison... < '2015-06-01'
No need to do the month or date math yourself, let MySQL do it for you. If you muck with adding 1 to the month, you have to handle the rollover from December to January, and increment the year. MySQL has all that already builtin.
date('t', strtotime("$year-$month-01")) will give days in the month
I currently have a query that is getting the records where their deadline is less than 3 months away. The deadline is stored as a Date, but the year is not important as this record should flag up every year.
My query:
SELECT client_name
FROM client
WHERE MOD(DAYOFYEAR(deadline) - DAYOFYEAR(CURDATE()), +365) <= 90
AND DAYOFYEAR(deadline) > DAYOFYEAR(CURDATE())
Apologies if there’s errors in the syntax as I’m writing this from memory – but it does work.
It works up until a deadline is in the first quarter and the current date is in the final quarter then it no longer returns the record. How do I get around this?
So the query needs to return the records that have a deadline within 3 months of the current date. The Year in the deadline date should be ignored as this could be years ago, but it is the day and month of the deadline that is important.
Or is the problem the date I am storing? Should I update this each year?
Thanks
One approach is to use a conditional test like this:
WHERE CONCAT(YEAR(NOW()),DATE_FORMAT(d.deadline,'-%m-%d'))
+ INTERVAL CONCAT(YEAR(NOW()),DATE_FORMAT(d.deadline,'-%m-%d'))<NOW() YEAR
< NOW() + INTERVAL 3 MONTH
We can unpack that a little bit. On that first line, we're creating a "next due" deadline date, by taking the current year, and appending the month and day value from the deadline.
But there's a problem. Some of those "next due" deadline dates are in the past. So, to handle that problem (when the 3 month period "wraps" into the next year), we need to add a year to any "next due" deadline date that's before the current date.
Now, we can compare that to a date 3 months from now, to determine if the "next due" deadline date is in the next 3 months.
That's a bit complicated.
Here's a SQL Fiddle as a demonstration: http://sqlfiddle.com/#!2/c90e9/3.
For testing, NOW() is inconvenient because it always returns today's date. So, for testing, we replace all occurrences of NOW() with a user-defined variable #now, and set that to various dates, so we can appropriately test.
Here's the SQL statement I used for testing. The first expression is the conditional test we're planning on using in the WHERE clause. For testing, we want to return all the rows, and just see which rows get due_in_3mo flagged as TRUE (1) and which get flagged as FALSE (0).
The second expression in the SELECT list just the "next due" deadline date, same as used in the first expression.
The rest of the expressions are pretty self-explanatory... we also want to display the date 3 months in the future we're comparing to, and the original "deadline" date value.
SELECT
CONCAT(YEAR(#now),DATE_FORMAT(d.deadline,'-%m-%d'))
+ INTERVAL CONCAT(YEAR(#now),DATE_FORMAT(d.deadline,'-%m-%d'))<#now YEAR
< #now + INTERVAL 3 MONTH
AS `due_in_3mo`
, CONCAT(YEAR(#now),DATE_FORMAT(d.deadline,'-%m-%d'))
+ INTERVAL CONCAT(YEAR(#now),DATE_FORMAT(d.deadline,'-%m-%d'))<#now YEAR
AS `next_due`
, d.id
, d.deadline + INTERVAL 0 DAY AS `deadline`
, #now + INTERVAL 3 MONTH AS `now+3mo`
, #now + INTERVAL 0 DAY AS `now`
FROM d d
CROSS
JOIN (SELECT #now := '2015-11-01') i
ORDER BY d.id
Change the value assigned to #now in the inline view (aliased as i) to test with other date values.
(You may want to use DATE(NOW()) in place of NOW() so that times don't get mixed in, and you may want to subtract another day from that, that really just depends how you want to handle the edge case of a deadline with month and day the same as the current date. (i.e. do you want to handle that as "in the past" or not.)
To summarize the approach: generate the "next due" deadline date as a DATE value in the future, and compare to the a date 3 months from now.
Hi I have a MySQL database which on I am setting up a table for a Study Calendar, fields are as follows:
SELECT
studycalendarpk,
studytopic,
`module`,
startdate,
enddate,
syllabusoutline
FROM studycalendar
What I am trying to do is to create a query so that for a dashboard php page it has a query that dispays the current weeks study programme. Can someone please tell me how to setup query to filter it so that it is selected if the current date is between the startdate and enddate, thank you
You have a startdate and an enddate for each row in your table, and if I understand your requirement correctly, you want to display all rows that meet these criteria.
WHERE enddate >= start of week
AND startdate < start of next week
You already have startdate and enddate in your table. This answer assumes that each row's enddate is constrained to be greater than or equal to the starttdate. If it isn't you'll get strange results.
You need a MySQL expression to compute the first day of the present week. Here's how you do that.
FROM_DAYS(TO_DAYS(CURDATE()) -MOD(TO_DAYS(CURDATE()) -1, 7))
This expression yields the Sunday immediately preceding CURDATE(). If your weeks are considered to start on Monday, use this instead (notice the -2).
FROM_DAYS(TO_DAYS(CURDATE()) -MOD(TO_DAYS(CURDATE()) -2, 7))
These are very useful expressions because they yield actual dates. Those dates can then be manipulated by date arithmetic such as somedate + INTERVAL 7 DAY which conveniently gives you the date a week later. This sort of arithmetic even works for the last week, and the first week, of a calendar year.
Putting it all together, here's what you do to select the records you want.
WHERE enddate >= FROM_DAYS(TO_DAYS(CURDATE())-MOD(TO_DAYS(CURDATE())-1,7))
AND startdate < FROM_DAYS(TO_DAYS(CURDATE())-MOD(TO_DAYS(CURDATE())-1,7))
+ INTERVAL 7 DAY
This will get the records from your table relevant to the current week.
SELECT *
FROM studycalendar
where curdate() between startdate and enddate
Can you try it? We can gett week no of use by this week() method
SELECT
`studycalendarpk`,
`studytopic`,
`module`,
`startdate`,
`enddate`,
CAST(week(now()) AS UNSIGNED)
syllabusoutline
FROM studycalendar WHERE CAST(week(now()) AS UNSIGNED) between CAST(week('2014-09-01') AS UNSIGNED) and CAST(week('2014-09-07') AS UNSIGNED)
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