CodeIgniter SQL查询 - 如何对每个月的值求和?

时间:2011-03-21 02:33:37

标签: php mysql codeigniter activerecord

我有下表:

//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

我想构建一个查询(如果可能的话,使用CI Active Records,但MySQL很好),我在其中生成以下结果:

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

           => [April 2011] [5]

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

           => [April 2011] [5]

我尝试使用$this->db->group_by,但我认为我没有正确使用它。

如果有人能给我一个指针或路线图来完成这项工作,我将不胜感激 - 谢谢!

2 个答案:

答案 0 :(得分:1)

这是一种非常激烈的方法,如果你需要频繁地进行这些查询,最好将月份作为列本身存储,但这基本上是它的工作方式:

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

这应该可以获得您正在寻找的结果集。

答案 1 :(得分:1)

样本表

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;

因为你想看到0行,你需要在年月和所有用户工厂之间进行交叉连接。

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无法正确排序的事实也需要在日期对日期进行复杂的处理。