簡體   English   中英

CodeIgniter SQL查詢 - 如何對每個月的值求和?

[英]CodeIgniter SQL query - how to sum values for each month?

我有下表:

//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但我認為我沒有正確使用它。

如果有人能給我一個指針或路線圖來完成這件事,我將不勝感激 - 謝謝!

這是一種非常激烈的方法,如果你需要頻繁地進行這些查詢,最好將月份作為列本身存儲,但這基本上是它的工作原理:

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

這應該會得到你正在尋找的結果集。

樣本表

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未正確排序的事實也需要在日期為訂購目的復雜處理日期。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM