我一直试图使用3张表制作资产负债表。第一个表是供应商的名称。第二个表是供应商和第三个表是向供应商付款,都与供应商表的外键相关联。
我期待的结果如下:
供应商名称-----------------------到期--------------------- ----------付款
名称------------------总和(数量* unitprice) ------------------总和(支付金额)
我的查询是
SELECT
tbl_supplier.supplier_name AS supplier,
SUM(tbl_payment.pay_amount) AS payment,
SUM(tbl_stock.stock_qnt * tbl_stock.stock_up) AS due
FROM
tbl_supplier
INNER JOIN
tbl_payment ON tbl_supplier.id = tbl_payment.supplier_id
INNER JOIN
tbl_stock ON tbl_supplier.id = tbl_stock.supplier_id
GROUP BY supplier_name
但结果是将到期金额与付款次数相乘,反之亦然。
例如,如果供应商的总应付金额为1000,并且已经支付了3次,则其显示的到期总额为3000,而不是1000。
请帮忙。谢谢
答案 0 :(得分:2)
您不能join
股票和付款表。 join
会将tbl_payment
中的每一行与tbl_stock
中的每一行合并,因此tbl_payment
中有3行,您将获得tbl_stock
中的1行原始行3次,然后总结这些。 Distinct
不是一个解决方案,因为它会忽略那些好的,不是不同的值,例如如果您实际有2笔100美元的付款,您将获得100美元的独特金额(因为100美元和100美元是相同的价值)。
您可以使用subquerys分别计算总和(这是隐含的join
tbl_supplier
tbl_payment
tbl_supplier
和tbl_stocks
SELECT
tbl_supplier.supplier_name AS supplier,
(select sum(tbl_payment.pay_amount)
from tbl_payment
where tbl_payment.supplier_id = tbl_supplier.id) as payment,
(select sum(tbl_stock.stock_qnt * tbl_stock.stock_up)
from tbl_stock
where tbl_stock.supplier_id = tbl_supplier.id) as due
from tbl_supplier;
,但不是全部三个一起):
"stdClass Object
(
[meta] => stdClass Object
(
[error_type] => APINotAllowedError
[code] => 400
[error_message] => you cannot view this resource
)
)"
答案 1 :(得分:0)
SELECT DISTINCT
tbl_supplier.supplier_name AS supplier,
SUM(DISTINCT tbl_payment.pay_amount) AS payment,
SUM(DISTINCT tbl_stock.stock_qnt * tbl_stock.stock_up) AS due
FROM
tbl_supplier
INNER JOIN
tbl_payment ON tbl_supplier.id = tbl_payment.supplier_id
INNER JOIN
tbl_stock ON tbl_supplier.id = tbl_stock.supplier_id
GROUP BY supplier_name