我有两张桌子:
product_in(存储所有产品数量)
Product Code(PK) Description QTY
RS121102 SUITS 100
RS129985 SUITS 100
DF-C09 SHIRTS 50
AE-H05 SHIRTS 50
product_out(存储所有售出的产品数量)
Product Code Description QTY
RS121102 SUITS 50
AE-H05 SHIRTS 10
我想要下面的结果
Product Code Description Total Qty Sold QTY
RS121102 SUITS 100 50
RS129985 SUITS 100 0
DF-C09 SHIRTS 50 0
AE-H05 SHIRTS 50 10
我该怎么做?
答案 0 :(得分:2)
SELECT pi.ProductCode, pi.Description, pi.QTY AS TotalQty,
ISNULL(po.QTY, 0) AS SoldQty
FROM product_in as pi
LEFT JOIN product_out as po
ON po.ProductCode = pi.ProductCode
假设product_out中的每个产品都没有多条记录。
答案 1 :(得分:0)
试试这个:
SELECT ProductCode, Description, SUM(Total_QTY) AS Total_Qty, SUM(Sold_Qty) AS Sold_Qty
FROM
(
SELECT ProductCode, Description, QTY As Total_Qty, 0 As Sold_Qty
from product_in
)
UNION ALL
(
SELECT ProductCode, Description, -QTY As Total_Qty, QTY As Sold_Qty
from product_out
)
GROUP BY ProductCode, Description