2

我有这个问题,关于如何从两个不同的表中求和总值,然后在得到它的总值后我想减去它。例如,我有表“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 对 sales 中的所有“总”值求和,并从 rsales 组中求和“total”值。然后在得到它的总和后,我想减去它。我的页面必须是这样的。

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

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

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

3 回答 3

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
于 2013-09-05T19:07:43.053 回答
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 子句中添加加法和减法。

于 2013-09-05T19:25:49.920 回答
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
于 2013-09-05T19:46:31.977 回答