Reputation: 3501
I have a table called Accounts which has a date column named TransactionDate. I need to get all the records where TransactionDate is between month,year.
For example, all records where TransactionDate is between 6, 2016 and 8, 2017.
My query string looks like:
SELECT Amount
FROM Accounts
WHERE (MONTH(TransactionDate) BETWEEN 6 and 8)
AND (YEAR(TransactionDate) BETWEEN 2016 and 2017)
ORDER BY TransactionDate ASC
However it only gives me records for June, July 2016 and August 2017. It skips the records for Jan 2017, Spet, Nov 2016.
I am attaching the screenshot of the TransactionDate column of all records (there are 31 of them)
Here is the screenshot of the returned result
What is wrong with my query? Also this query is going to be dynamic, i.e. users will choose the month and year from a form and the result will be returned to them.
Thank you.
Upvotes: 0
Views: 1030
Reputation: 2049
You can do this easily by using date_format function of mysql
SELECT
Amount
FROM
Accounts
WHERE
DATE_FORMAT(TransactionDate, '%Y-%m') BETWEEN '2016-06' AND '2017-08' ORDER BY TransactionDate ASC;
This should work perfectly.
Upvotes: 0
Reputation: 184
You simply filter the queries by those that are BEFORE 2017-08 and AFTER 2016-06
SELECT Amount
FROM Accounts
WHERE TransactionDate > '2016-06-01T00:00:00'
AND TransactionDate < '2017-08-01T00:00:00'
ORDER BY TransactionDate ASC
what's wrong with your current query is that you're getting data where the month is June, July, or August, AND where the year is 2016 or 2017. This isn't right, you want to filter by the Date itself, not it's components.
Upvotes: 1
Reputation: 18592
I think this what you need
SELECT Amount , ExpenseType ,
MONTHNAME(TransactionDate) AS TransactionMonthString
Year(TransactionDate) AS TransactionYearString
FROM Accounts
WHERE TransactionDate >= '2016-06-01' AND TransactionDate <= '2017-08-01'
ORDER BY TransactionDate
Upvotes: 0
Reputation: 496
select Amount from Accounts where TransactionDate BETWEEN '2016-04-02' AND '2017-08-03';
try this,good luck
Upvotes: 0
Reputation: 1269445
You would seem to want:
select a.Amount
from Accounts a
where a.TransactionDate >= '2016-06-01' AND
a.TransactionDate < '2017-09-01'
order by a.TransactionDate ASC
Upvotes: 0