求和两个不同的表并减去其总数

时间:2013-09-05 18:38:31

标签: php mysql

我有这个问题,如何从两个不同的表中总和总值,然后在得到它的总数后我想减去它。例如我有表“rsales”和“sales”,我在下面有这些ff vlue。

来自“rsales”的数据

id | total | pcode |
1  | 100   | 2143  |
2  | 100   | 2143  |
3  | 50    | 2222  |
4  | 50    | 2222  |

来自“销售”的数据

id | total | pcode |
7  | 100   | 2143  |
8  | 50    | 2222  |

我的问题是这个。我想从销售额中总结所有“总”值,并通过pcode从sumales group求和“total”值,然后在得到它的总和后我想减去它。我的页面必须是这样的。

   total    pcode
 | 100    | 2143  |
 | 50     | 2222  |

我有这个ff代码,但它不适合我

sql "select sum(rsales.total)- sum(sales.total) as t1 where pcode = rsales.pcode"

3 个答案:

答案 0 :(得分:1)

使用:

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;

输出:

+--+--+--+--+--+-
| total | pcode |
+--+--+--+--+--+-
| 100   | 2143  |
| 50    | 2222  |
+--+--+--+--+--+-
2 rows in set

答案 1 :(得分:0)

你尝试过这样的事吗?

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

如果从两个表中获得预期值,您可以轻松地在FROM子句中添加Additions和Subtruction。

答案 2 :(得分:0)

这样做不需要加入。如果某些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