Select idn, sum(tblppmp.total_item) as a_total
sum(tblRequest.Quantity) as b_total
sum(a_total- b_total) as itemsleft
FROM PPMP.dbo.tblppmp, ppmp.dbo.tblrequest
Group by idn


我有我的问题,如何对table1和table2中的各个项目求和,结果将被减去以获得答案。

像这样

table1
id     item
1        2
2        3
3        4


表2

id       item
1        1
2        2
3        3


我想要的结果是这样的。

表3

sum(table.item)-sum(table2.item)

table1.id 1 = 2
table2.id 1 = 1
so (2-1) = 1

id     item_left
1      1
2      1
3      1


ID项目

最佳答案

您可以先计算每个表的总和,然后减去它们。

select  idn,
        a_total - ISNULL(r_total,0) as itemsleft
FROM
(
    select idn, sum(p.total_item) as p_total
    from    PPMP.dbo.tblppmp p
    group by idn
) p
LEFT JOIN
(
    select idn, sum(r.Quantity) as r_total
    from    ppmp.dbo.tblrequest r
    group by idn
) r on p.idn = r.idn

关于mysql - SQL查询选择表1和表2的总和减去它们,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44621237/

10-12 20:19