0

我有两张桌子:

  1. product_in(存储所有产品数量)

    Product Code(PK)     Description                QTY
    RS121102             SUITS                      100
    RS129985             SUITS                      100
    DF-C09               SHIRTS                     50
    AE-H05               SHIRTS                     50
    
  2. 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

我怎样才能做到这一点?

4

2 回答 2

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 中的每个产品都没有多条记录。

于 2013-05-02T23:25:43.573 回答
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
于 2013-05-02T23:40:59.157 回答