mysql - sum of value of each month of year -
i want query in mysql sum of value every month on year.
currently have this:
select e.rfc rfc, sum(f.total) total, month(f.fecha) mes foo f inner join bar e on f.bar_id = e.id inner join baz u on e.baz_id = u.id u.id = 3 , date(f.fecha) between '2014-01-01' , '2014-12-31' group month(f.fecha)
but in months doesn't exist foo values not showing.
my result atm it's 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 return 0.0 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 fill chart , need 0 when no foo values available sum.
thank you.
assuming have data user in each month each rfc
, easy way fix using conditional aggregation:
select e.rfc rfc, sum(case when u.id = 3 f.total else 0 end) total, month(f.fecha) mes foo f inner join bar e on f.bar_id = e.id inner join baz u on e.baz_id = u.id date(f.fecha) between '2014-01-01' , '2014-12-31' group month(f.fecha) ;
if doesn't work, have start mucking around left join
, generating rows 12 months of each each rfc
.
edit:
here more painful version:
select sum(total), m.m (select distinct month(f.fecha) m foo date(f.fecha) between '2014-01-01' , '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 , u.id = 3 group m.m order m.m;
i don't know rfc
value doing. coming arbitrary row , doesn't belong in query.
Comments
Post a Comment