I have a table named nca and heres what it looks like with values :
+--------+---------+------------+------------+--------------+---------+ | nca_id | nca_no | issue_date | nca_amount | account_type | balance | +--------+---------+------------+------------+--------------+---------+ | 1 | 14-0001 | 2015-01-08 | 200000 | ROP | 0 | | 2 | 14-0002 | 2015-01-08 | 400000 | ROP | 0 | | 3 | 14-0003 | 2015-02-02 | 1000000 | ROP | 0 | | 4 | 14-0004 | 2015-02-02 | 300000 | ROP | 0 | | 5 | 14-0001 | 2015-01-08 | 250000 | DBP-TRUST | 0 | | 6 | 14-0002 | 2015-01-08 | 400000 | DBP-TRUST | 0 | +--------+---------+------------+------------+--------------+---------+
Now using this query it can display the SUM of the nca_amount base on the issue_date:
SELECT SUM(nca_amount) FROM nca WHERE account_type = 'ROP' AND issue_date = '2015-02-02'
which gives a result of 1300000 since it adds all the amount that having a date of 2015-02-02 and just works fine if you set the date just on the query itself.
But I have scenario that I want to solve. I have an html form where the user could enter the date he want.
And if the user would type the date of 2015-02-23, I want this date input referring to the issue_date of 2015-02-02 from my table. What I want is if the date input is in the RANGE of the MONTH of the issue_date on the nca table, this would refer to the issue_date found on the nca table and display the sum. For example :
user input_date = '2015-02-23' referring to issue_date = '2015-02-02'
as the inputted date is in the range of '2015-02-02' found on my nca table and then it can display the sum like on my query above. How can I do this query? Can any one help with this one? thanks in advance.
If you want to match the month:
SELECT SUM(nca_amount)
FROM nca
WHERE account_type = 'ROP' AND
year(issue_date) = year('2015-02-02') and
month(issue_date) = month('2015-02-02');
However, this doesn't allow the query to use an index on issue_date
. For that, you need to rephrase the query as:
SELECT SUM(nca_amount)
FROM nca
WHERE account_type = 'ROP' AND
issue_date >= date(concat(left('2015-02-02', 7), '-01')) and
issue_date < date(concat(left('2015-02-02', 7), '-01')) + interval 1 month;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.