CodeIgniter SQL 查询 - 如何对每个月的值求和?
我有下表:
//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
但我认为我没有正确使用它。
如果有人能给我一个指导或路线图来完成这项工作,我将不胜感激 - 谢谢!
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 have tried using $this->db->group_by
but I think I'm not using it correctly.
If anyone could give me a pointer or roadmap to get this done it would be much appreciated -- thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
示例表
因为您想要查看带有 0 的行,所以您需要在年-月和所有用户工厂之间进行交叉连接。
Month Year
排序不正确的事实还需要对日期进行复杂的处理,以便在最后进行排序。Sample table
Because you want to see the row with 0, you need to do a cross join between the year-month and all user-plants.
The fact that
Month Year
does not sort correctly also requires the complex treatment of the dates for ordering purposes at the end.这是一种非常激烈的方法,如果您需要经常进行这些查询,最好将月年存储为列本身,但这基本上就是它的工作原理:
这应该会为您提供结果集正在寻找。
This is a pretty intense way to do it and it would be far preferable to store the month-year as a column itself if you need to make these queries frequently, but this is basically how it works:
That should get you the resultset you're looking for.