[英]sum two different table and the subtract its total
i have this problem with me on how to sum total value from two different table and then after getting its total i want to subtract it. 我对如何从两个不同的表中求和,然后求和后总和我想减去它。 for example i have table "rsales" and "sales" and i have these ff vlue below.
例如我有表“销售”和“销售”,我在下面有这些ff vlue。
data from "rsales" 来自“销售”的数据
id | total | pcode |
1 | 100 | 2143 |
2 | 100 | 2143 |
3 | 50 | 2222 |
4 | 50 | 2222 |
data from "sales" 来自“销售”的数据
id | total | pcode |
7 | 100 | 2143 |
8 | 50 | 2222 |
my problem is this. 我的问题是这个。 i want to sum all "total" values from sales and sum "total"value from rsales group by pcode.and then after getting its sum i want to subtract it.
我想对所有来自销售的“合计”值求和,并通过pcode。从rsales组求和“合计”值。 my page must be something like this.
我的页面必须是这样的。
total pcode
| 100 | 2143 |
| 50 | 2222 |
i have this ff code but it doesnt wor for me 我有这个ff代码,但我不满意
sql "select sum(rsales.total)- sum(sales.total) as t1 where pcode = rsales.pcode"
Use: 采用:
SELECT
SUM(r.total)-(
SELECT SUM(s.total)
FROM sales AS s WHERE r.pcode=s.pcode
) as total,
r.pcode
FROM rsales AS r
GROUP BY r.pcode;
Output: 输出:
+--+--+--+--+--+-
| total | pcode |
+--+--+--+--+--+-
| 100 | 2143 |
| 50 | 2222 |
+--+--+--+--+--+-
2 rows in set
Have you tried something like this? 你尝试过这样的事情吗?
SELECT
SUM(L.total) as lTotal, SUM(R.total) as rTotal
FROM
sales L
INNER JOIN rsales R
ON
R.pcode = L.pcode
GROUP BY L.pcode
If you get expected values from both tables you can easily add Additions and Subtruction in FROM clause. 如果从两个表中都获得期望值,则可以在FROM子句中轻松添加Additions和Subtruction。
There's no joins needed to do this. 无需加入即可执行此操作。 This solution works if some pcodes are only in one table:
如果某些pcode仅在一个表中,则此解决方案有效:
select SUM(total), pcode from (
select sum(total) as total, pcode from rsales group by pcode
union all
select SUM(-total) as total, pcode from sales group by pcode) salesTables
group by pcode
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.