简体   繁体   中英

How to subtract rows of similar columns and values from two datatables

在此处输入图片说明

How to subtract values from two sql datatables? In the pic I have two datatable where I want to first match table1 "partnum" columns and if its match with table 2 "partnum" then subtract table1 "FinalstockIN"values from table2"FinalStockout" then display it in another column.

What I have tried from others suggestion but this does not show full datas too.

with spare_parts as (

SELECT s.partnum,partdesc,partmodel,stockin,dateofstockin, (SELECT 
SUM(stockin)
FROM Tbl_SpareParts
GROUP BY partnum
HAVING partnum = s.partnum) AS FinalTotalStockIN FROM Tbl_SpareParts s
),
cases as (
SELECT 
b.partnum,partdesc,partmodel,outstock,outstockdate,
outstockcaseid_billnum,remarks, (SELECT SUM(outstock)
FROM Tbl_OutCaseID
GROUP BY partnum
HAVING partnum = b.partnum) AS FinalTotalStockOut FROM Tbl_OutCaseID b
)
select
s.partnum, s.partdesc, s.partmodel, s.stockin, 
s.dateofstockin, s.FinalTotalStockIN,
c.partnum AS Stockoutpartnum, 
c.partdesc AS Stockoutpartdesc, 
c.partmodel AS stockoutpartmodel, c.outstock, 
c.outstockdate, c.outstockcaseid_billnum, 
c.remarks, c.FinalTotalStockOut
from
spare_parts s
join cases c on s.partnum = c.partnum

SELECT STOCKOUTPARTNUM,STOCKOUTPARTNUM,NULL FROM TABLE 2 MINUS SELECT PARTNUM,NULL,PARTNUM FROM TABLE 1

数据类型必须与STOCKOUTPARTNUM,PARTNUM相同

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