Mysql Sum group by with two tables sums两次或更多次(更改)

时间:2015-11-15 11:49:38

标签: php mysql

在查询中花了很多钱来结果。我收到了错误的答案。

Ledger Table

详情| CR |博士| TDS |借记

P-01 | 500 | 0 | 50 | 50

P-02 | 1500 | 0 | 0 | 0

P-01 | 7500 | 0 | 0 | 0

固定| 0 | 100 | 0 | 0

Billing_details表

bill_no | party_com_name | TOTAL_COST

BILL-01 | P-01 | 2500

BILL-02 | P-02 | 4000

BILL-03 | P-01 | 9000

派对表

P_ID | party_com_name

P-01 | ABC

P-02 | XYZ

我希望输出为

party_com_name | TOTAL_COST | paidamt | pendingamt

AA | 11500 | 8000 | 3500

BB | 4000 | 1500 | 2500

上述结果的公式:

total_cost =来自同名帐单明细的所有total_cost的总和

paidamt =来自同名分类帐的cr + tds +借方总和

来自结果的

pendingamt = total_cost-paidamt

请帮忙

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT 
Billing_details.party_com_name,
SUM(Billing_details.total_cost) AS total_cost,
SUM(Ledger.cr) AS paidamt,
(total_cost - paidamt) AS pendingamt 
FROM 
Billing_details
INNER JOIN Ledger
ON Ledger.bill_no = Billing_details.bill_no
GROUP BY Billing_details.party_com_name;

答案 1 :(得分:0)

<强>查询: -

SELECT billing_details.party_com_name,SUM(billing_details.`total_cost`) `total_cost`, SUM(ledger_table.`cr`) `paidamt` ,  ((SUM(billing_details.`total_cost`))-(SUM(ledger_table.`cr`))) as `pendingamt`
FROM billing_details
INNER JOIN ledger_table
ON
billing_details.bill_no = ledger_table.bill_no
GROUP BY billing_details.party_com_name