我正在使用cakephp 1.3。我的收入表中有日期字段。我正在尝试循环获取每月总收入。以下是我的查询。
$income_and_hst = $Income->find('all', array(
'fields' => array('SUM(Income.amount) as income',
'SUM(Income.hst_amount) as hst',
'MONTH(date) as month'),
'conditions' => array(
'Income.income_account_id' => array(1,2,3,4),
'Income.user_id' => $this->Auth->user('id'),
'Income.account_id' => $this->Session->read('Account.default_account'),
'Income.date >' => $starting_date,
'Income.date <' => $ending_date,
),
'group' => 'MONTH(date)',
)
);
这给了我 5 个月的收入。因为收入是5个月的。即使其他月份没有收入,我也需要显示所有 12 个月。如果没有收入,我希望该月收入为 0。
有人可以给我指点吗?
谢谢。
最佳答案
我的猜测是你不能使用该界面来做到这一点。您要么需要深入研究原始 SQL(和交叉连接),要么在周围的 php 代码中添加缺少的月份。我建议后者应该可以工作(伪代码,我不记得 php 语法):
for ($row in $income_and_hst) {
$income_and_hst_all[$row['month']] = $row
}
for ($month = 1;$month <= 12; $month++) {
if ($income_and_hst_all[$month] == nil) {
$income_and_hst_all[$month] = Array (
'income' => 0,
'hst' => 0,
'month' => $month
)
}
}
关于mysql - 如何在 MySQL 中按所有 12 个月进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19072306/