简体   繁体   中英

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.

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. my page must be something like this.

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

i have this ff code but it doesnt wor for me

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.

There's no joins needed to do this. This solution works if some pcodes are only in one table:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM