SQL从不同的表中减去

时间:2018-03-15 07:20:02

标签: sql sql-server

我有来自两个表的两个不同的查询。我的第一个查询是:

select sum(total_amount) as total_amount, supplier_name 
from tbL_supplierAccountLedger 
where DATE >= '2017-01-01' and DATE <= '2017-12-31'  group by supplier_name 

这是

的输出
Total Amount | Supplier name

4000               A
5000               B
8000               C
9000               D

这是我的另一个具有不同tablename

的查询
SELECT SUM(RET_AMOUNT)as returnamount, SUPPLIER_NAME  
FROM tbl_PurchaseReturns
where CAST(date as DATE) >= '2017-01-01' and 
CAST(date as DATE) <= '2017-12-31'
group by SUPPLIER_NAME

这是

的输出
Return Amount | Supplier name

1000               A
2000               B
500                C

我想要一个自动从表A中减去表B的查询。 以下是预期产量。

total amount | Supplier Name 
3000             A 
3000             B 
7500             C 
9000             D

2 个答案:

答案 0 :(得分:3)

使用派生查询和union两个结果,将tbl_PurchaseReturns的RET_AMOUNT作为负值。最后按supplier_name分组

SELECT SUM(total_amount), supplier_name 
FROM
(

    SELECT sum(total_amount) as total_amount, supplier_name 
    from   tbL_supplierAccountLedger 
    where  DATE >= '2017-01-01' and DATE <= '2017-12-31'  
    group by supplier_name 

    UNION ALL

    SELECT SUM(-RET_AMOUNT) as returnamount, supplier_name 
    FROM   tbl_PurchaseReturns
    where  CAST(date as DATE) >= '2017-01-01' 
    and    CAST(date as DATE) <= '2017-12-31'
    group by supplier_name 

) AS D
GROUP BY supplier_name 

答案 1 :(得分:2)

执行JOIN s

SELECT s.supplier_name, 
       r.total_amount - coalesce(returnamount, 0) as amount from
(
    SELECT supplier_name , SUM(total_amount) as total_amount
    FROM tbL_supplierAccountLedger 
    WHERE ...  
    GROUP BY supplier_name 
)s LEFT JOIN (
     SELECT SUPPLIER_NAME , SUM(RET_AMOUNT)as returnamount
     FROM tbl_PurchaseReturns
     WHERE ...
     GROUP BY SUPPLIER_NAME
) r on r.SUPPLIER_NAME= s.supplier_name