Reputation: 369
I want to do a query in MySQL to get the sum of a value from every month on a year.
currently i have something like this:
SELECT
e.rfc as RFC,
SUM(f.total) AS Total,
MONTH(f.fecha) as Mes
FROM
foo f
INNER JOIN
bar e
ON f.bar_id = e.id
INNER JOIN
baz u
ON e.baz_id = u.id
WHERE
u.id = 3
AND DATE(f.fecha) BETWEEN '2014-01-01' AND '2014-12-31'
GROUP BY
MONTH(f.fecha)
But in months where doesn't exist foo values are not showing.
My result atm it's something like:
RFC Total Mes
AAA010101AAA 10556.000000 12
AAA010101BBB 1856.000000 11
AAA010101BBB 66262.896800 10
AAA010101BBB 990.090000 9
AAA010101BBB 73.000000 8
AAA010101BBB 1304761.620000 7
My desired result are:
RFC Total Mes
AAA010101AAA 10556.000000 12
AAA010101AAA 0.0 11
... (When no data it's available just return 0.0 for the month)
AAA010101AAA 0.0 1
AAA010101BBB 0.0 12
AAA010101BBB 1856.000000 11
AAA010101BBB 66262.896800 10
AAA010101BBB 990.090000 9
AAA010101BBB 73.000000 8
AAA010101BBB 1304761.620000 7
AAA010101BBB 0.0 6
...
AAA010101BBB 0.0 1
I want to fill a chart and i need a zero when no foo values are available to sum.
Thank you.
Upvotes: 1
Views: 94
Reputation: 1269463
Assuming you have data for some user in each month for each rfc
, an easy way to fix this is using conditional aggregation:
SELECT e.rfc as RFC,
SUM(CASE WHEN u.id = 3 THEN f.total ELSE 0 END) AS Total,
MONTH(f.fecha) as Mes
FROM foo f INNER JOIN
bar e
ON f.bar_id = e.id INNER JOIN
baz u
ON e.baz_id = u.id
WHERE DATE(f.fecha) BETWEEN '2014-01-01' AND '2014-12-31'
GROUP BY MONTH(f.fecha) ;
If this doesn't work, you have to start mucking around with left join
and generating rows for the 12 months of the each for each rfc
.
EDIT:
Here is the more painful version:
select sum(total), m.m
from (select distinct month(f.fecha) as m from foo where DATE(f.fecha) BETWEEN '2014-01-01' AND '2014-12-31' ) m left join
foo f
on month(f.fecha) = m.m left join
bar e
ON f.bar_id = e.id left join
baz u
ON e.baz_id = u.id and u.id = 3
group by m.m
order by m.m;
I don't know what the rfc
value is doing. It is coming from an arbitrary row and doesn't really belong in the query.
Upvotes: 1