Reputation: 21
How can we get record of first or second month of current year in MySQL query?
Like I want this data for January and then for February:
select Sum(amount) as Amount from tbl_incomes where created_at = 'here the month January OR February of current year should be claused'
Upvotes: 0
Views: 1065
Reputation: 37497
You should use a range expression.
SELECT sum(amount) amount
FROM tbl_incomes
WHERE created_at >= concat(year(now), '-01-01')
AND created_at < concat(year(now), '-03-01');
That way an index on created_at
can support the query.
Upvotes: 0
Reputation: 43604
You can use the following, using YEAR
and MONTH
:
SELECT SUM(amount) AS Amount
FROM tbl_incomes
WHERE YEAR(created_at) = YEAR(NOW()) AND MONTH(created_at) IN (1, 2)
In case you want the SUM
for January and February in separate rows you can use this:
SELECT SUM(amount) AS Amount
FROM tbl_incomes
WHERE YEAR(created_at) = YEAR(NOW()) AND MONTH(created_at) IN (1, 2)
GROUP BY YEAR(created_at), MONTH(created_at)
Upvotes: 1