Sql查询选择table1的总和和table2的总和并减去它们

时间:2017-06-19 01:52:59

标签: mysql sql-server sql-server-2008

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 item

2 个答案:

答案 0 :(得分:0)

您无法使用sum(a_total- b_total)。您必须使用sum(tblppmp.total_item) - sum(tblRequest.Quantity)

Select tblppmp.idn
, tblppmp.total_item as a_total 
,tblRequest.Quantity as b_total 
,tblppmp.total_item - tblRequest.Quantity as itemsleft 
FROM dbo.tblppmp 
INNER JOIN 
(SELECT
tblrequest.idn
,sum(tblRequest.Quantity) AS Quantity
FROM tblrequest 
WHERE tblrequest.dr_year = 2015
GROUP BY tblrequest.idn) tblrequest ON tblppmp.idn = tblrequest.idn

答案 1 :(得分:0)

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

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