我正在使用Cakephp 2.x并且在MYSQL选择连接查询的SUM时遇到以下问题
我有两张名为AccountVoucher& amp; VoucherDetails
AccountVoucher
+----------+-------------+-------------+
|voucherId | voucherDate | Decription |
+----------+-------------+-------------+
| 1 | 2014-07-05 | Test DFF |
+----------+-------------+-------------+
| 2 | 2014-07-02 | Tf DrtF |
+----+-----+-------------+-------------+
| 3 | 2014-07-05 | Tedgt afF |
+----------+-------------+-------------+
| 4 | 2014-07-03 | hdt faF |
+----------+-------------+-------------+
VoucherDetails
+-----------+-----------+-------------+-------------+------------+
| DetailsID | voucherId | DebitAmount | CreditAmount| AccHead |
+-----------+-----------+-------------+-------------+------------+
| 1 | 2 | 1200 | 1000 | AB |
+-----------+-----------+-------------+-------------+------------+
| 2 | 2 | 1000 | 700 | AB |
+-----------+-----------+-------------+-------------+------------+
| 3 | 4 | 500 | 400 | GH |
+-----------+-----------+-------------+-------------+------------+
| 4 | 3 | 1500 | 500 | GH |
+-----------+-----------+-------------+-------------+------------+
VoucherDetails表必须从AccountVoucher表和
加入我需要获得每个AccHeads AB和GH的借方总金额和贷方金额,
,结果应为
+----------+-------------+-------------+
|AccHead | TotalDebit | TotalCredit |
+----------+-------------+-------------+
| AB | 2200 | 1700 |
+----------+-------------+-------------+
| GH | 2000 | 900 |
+----------+-------------+-------------+
请帮助......
答案 0 :(得分:1)
你需要的sql语句是(目前还不清楚为什么你需要JOIN来获得你需要的结果):
SELECT AccHead, SUM(DebitAmount) AS TotalDebit, SUM(CreditAmount) AS TotalCredit
FROM VoucherDetails
GROUP BY AccHead;
要在VoucherDetail模型中将其转换为CakePHP:
$this->find('all',
'fields' => array(
'AccHead',
'SUM(DebitAmount) AS TotalDebit',
'SUM(CreditAmount) AS TotalCredit'),
'group' => 'AccHead')
答案 1 :(得分:0)
工作正常。如果需要,请加载您的模型。
$query = "select b.AccHead, sum(b.DebitAmount) as TotalDebit ,
sum(b.CreditAmount) as TotalCredit from AccountVoucher as a ,
VoucherDetails as b where a.voucherId = b.voucherId group by AccHead";
$this->ModelName->query($query);
您也可以使用
$this->find('all',
'conditions' => array('AccountVoucher.voucherId' => 'VoucherDetails.voucherId'),
'fields' => array(
'AccHead',
'SUM(DebitAmount) as TotalDebit',
'SUM(CreditAmount) as TotalCredit'),
'group' => 'AccHead');