CodeIgniter SQL query - how to sum values ​​for each month?

I have the following table:

//table_1

record_id   user_id    plant_id    date        cost
1           1          1           2011-03-01   10
2           1          1           2011-03-02   10
3           1          1           2011-04-10   5
4           1          2           2011-04-15   5

I would like to build a query (if possible using CI Active Records, but MySQL is fine) in which I generate the following result:

[1] => [1] => [March 2011] [20]

           => [April 2011] [5]

       [2] => [March 2011] [0]

           => [April 2011] [5]

I tried using $this->db->group_by, but I think that I am not using it correctly.

If anyone could give me a signpost or roadmap to do this, that would be very appreciated - thanks!

+3
source share
2 answers

Table example

drop table if exists t;
create table t( record_id int, user_id int, plant_id int, date datetime, cost float);
insert t select
1 ,1, 1 ,'2011-03-01', 10 union all select
2 ,1, 1 ,'2011-03-02', 10 union all select
3 ,1, 1 ,'2011-04-10', 5 union all select
4 ,1, 2 ,'2011-04-15', 5;

Since you want to see the line with 0, you need to cross-connect between the annual month and all user settings.

select up.user_id, up.plant_id, ym2, ifnull(sum(t.cost),0) totalcost
from (select distinct date_format(date, '%Y-%m') ym, date_format(date, '%M %Y') ym2 from t) dates
cross join (select distinct t.user_id, t.plant_id from t) up
left join t on date_format(t.date, '%Y-%m') = dates.ym
           and up.user_id=t.user_id
            and up.plant_id=t.plant_id
group by up.user_id, up.plant_id, ym2, ym
order by up.user_id, up.plant_id, date(concat(ym,'-1'));

, Month Year , .

+1

, - , , :

SELECT CONCAT(MONTHNAME(date), ' ', YEAR(date)) AS monthyear, COUNT(*) AS count GROUP BY YEAR(date), MONTH(date), plant_id;

.

+1

All Articles