加入 2 table 以计算每个东西的数量的查询是什么

what is the query to join 2 table to calculate qty per stuff

是否可以创建连接 2 table 的查询来计算每个代码的总数量?我正在使用 SQL Server 2008。

我有 table 购买

id_Purchase| stuff_code| qty
------------------------------
1          | G-001     | 6000
2          | G-002     | 4000
3          | G-003     | 2000
4          | G-001     | 5000

和table销售

id_selling| id_purchase| qty
------------------------------
1         | 1          | 2000
2         | 1          | 3000
3         | 2          | 1000

id_purchase 是来自 table 购买的外键

我想要的是生成这个的查询

stuff_code| qty
-----------------
G-001     | 6000
G-002     | 3000
G-002     | 2000

请注意 G-001 数量为 6000 + 5000 - 2000 - 3000

这是我当前的查询

SELECT stuff_code, SUM(P.qty)-ISNULL(SUM(S.qty),0)
FROM Purchase P LEFT JOIN Selling S ON P.ID_Purchase = S.ID_Purchase
GROUP BY stuff_code

结果是

stuff_code| qty
-----------------
G-001     | 12000
G-002     | 3000
G-002     | 2000

您有两种不同粒度的数据集。以相同的粒度获取它们,您可以直接进行数学计算。

SELECT p.ID_Purchase
, p.stuff_code
, p.StuffPurchased
, ISNULL(s.StuffSold,0) as StuffSold
, p.StuffPurchased - ISNULL(s.StuffSold,0) as StuffLeft
FROM (SELECT
ID_Purchase
, stuff_code
, SUM(Qty) StuffPurchased
FROM Purchase
GROUP BY ID_Purchase
, stuff_code) p 
LEFT JOIN (
SELECT ID_Purchase
, SUM(Qty) StuffSold
FROM Selling
GROUP BY ID_Purchase) s
ON P.ID_Purchase = S.ID_Purchase

试试这样的东西:

SELECT table1.id_purchase, table1.stuff_code, table1.sum - table2.sum
FROM 
((SELECT id_purchase, stuff_code, SUM(qty) sum
  FROM Purchase
  GROUP BY id_purchase) AS table1
  INNER JOIN
  (SELECT id_purchase, SUM(qty) sum
   FROM SELLING
   GROUP BY id_purchase) AS table2
  ON table1.id_purchase = table2.id_purchase);

下面是一种方法,使用 stuff_code 的常用 table 表达式进行采购和销售汇总。

CREATE TABLE dbo.Purchase(
      id_Purchase int
        CONSTRAINT PK_Purchase PRIMARY KEY
    , stuff_code varchar(10)
    , qty int
    );

INSERT INTO dbo.Purchase VALUES
     (1, 'G-001', 6000)
    ,(2, 'G-002', 4000)
    ,(3, 'G-003', 2000)
    ,(4, 'G-001', 5000);


CREATE TABLE dbo.Selling(
      id_selling int
        CONSTRAINT PK_Selling PRIMARY KEY
    , id_purchase int
    , qty int
    );

INSERT INTO dbo.Selling VALUES
      (1, 1, 2000)
    , (2, 1, 3000)
    , (3, 2, 1000);

WITH
    purchase_summary AS (
        SELECT stuff_code, SUM(qty) AS qty
        FROM dbo.Purchase
        GROUP BY stuff_code
    )
    ,sales_summary AS (
        SELECT p.stuff_code, SUM(s.qty) AS qty
        FROM dbo.Selling AS s
        JOIN dbo.Purchase AS p ON
            p.id_purchase = s.id_purchase
        GROUP BY p.stuff_code
    )
SELECT 
      purchase_summary.stuff_code
    , purchase_summary.qty - COALESCE(sales_summary.qty, 0) AS qty
FROM purchase_summary
LEFT JOIN sales_summary ON
    sales_summary.stuff_code = purchase_summary.stuff_code
ORDER BY
    stuff_code;