![](/img/trans.png)
[英]subtract two different sum of column from two different table in select query
[英]subtract from two different table
我有3个表“产品列表,销售,退货”表,因此,例如,我有3个销售和2个退货,如下所示。
这是产品列表中的数据
id | pcode | pname | pdesc |
1 | 222 | 33uf | 10v |
这是来自销售的ff数据
id | pcode | total | profit
1 | 222 | 200 | 10
2 | 222 | 100 | 10
3 | 222 | 200 | 10
这是返回的ff数据
id | pcode | total | lose
3 | 222 | 200 | 10
4 | 222 | 100 | 10
我的问题是这个 。 我想选择产品列表数据, 总结销售“总”和“利”的价值,总结了“总”,并从返回“丢失”的价值。 然后减去我的两个表以获得结果。 预期结果必须是这样的。
id | pcode | pname | pdesc | total | profit |
1 | 222 | 33uf | 10v | 200 | 10 |
我有这个ff代码,但是我不能从销售中减去“总计”,从收益中减去“总计”,从销售中减去“利润”,从收益中减去“亏损”。
$result = mysql_query("SELECT
productlist.*,
SUM(sales.total)-SUM(return.total) as total,
SUM(sales.profit)-SUM(return.lose) as profit
FROM productlist
LEFT JOIN sales ON sales.pcode = productlist.pcode AND return ON return.pcode = productlist.pcode
GROUP BY pcode
ORDER BY total ASC");
您似乎正在尝试使用AND
将两个表连接起来,这不太正确;)
尝试这个:
...
LEFT JOIN `sales` USING (`pcode`)
LEFT JOIN `return` USING (`pcode`)
...
我不确定这是否可行,它可能会抱怨column `pcode` is ambiguous
。 如果发生这种情况,请尝试以下方法:
...
LEFT JOIN `sales` ON `sales`.`pcode` = `productlist`.`pcode`
LEFT JOIN `return` ON `return`.`pcode` = `productlist`.`pcode`
...
您的查询结构不会返回正确的结果。 无论您如何固定语法,都将在给定产品的销售和退货之间获得笛卡尔产品。
一种解决方法是在联接之前进行聚合:
SELECT pl.*,
(coalesce(s.total, 0) - coalesce(r.total, 0)) as total,
(coalesce(s.profit, 0) - coalesce(r.lose, 0)) as profit
FROM productlist pl left join
(select pcode, sum(total) as total, sum(profit) as profit
from sales
group by pcode
)
on s.pcode = pl.pcode left join
(select pcode, sum(total) as total
from return
group by pcode
) r
on r.pcode = pl.pcode
ORDER BY total ASC;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.