通过在基础颜色上添加列来计算可用库存

时间:2017-09-25 06:42:42

标签: sql sql-server

我试图在sql中计算库存。我有4个表产品,尺寸,购买和销售。产品表是

+----+------------------+
| id | product_name     | 
+----+------------------+
| 1  | apple            | 
|----|------------------|
| 2  |banana            | 
|----|------------------|
| 3  |mango             | 
+----+------------------+

现在颜色表

+----+------------------+
| id |   color_name     | 
+----+------------------+
| 1  |   dark           | 
|----|------------------|
| 2  |   light          | 
+----|------------------+

购买表是

+-------+-------------+
| id    | quantity    |color
+-------+-------------+
|   1   |   15        |dark
+-------+-------------+
|   1   |   10        |light
+-------+-------------+
|   2   |   5         |dark
+-------+-------------+
|   3   |   25        |light
+-------+-------------+

和销售表是

+-------+-------------+
| id    | quantity    |color
+-------+-------------+
|   1   |   5         |dark
+-------+-------------+
|   1   |   5         |light
+-------+-------------+
|   2   |   5         |dark
+-------+-------------+
|   3   |   5         |light
+-------+-------------+

购买和销售表具有产品表的外键ID引用ID。现在我试图以颜色为基础计算可用库存,即以下格式的购买和销售差异

+----+------------------+-------------+
| id | product_name     | quantity    |color
+----+------------------+-------------+
| 1  | apple            |    10       |dark
|----|------------------|-------------|
| 1  | apple            |    5        |light
|----|------------------|-------------|
| 2  |banana            |    0        |dark
|----|------------------|-------------|
| 3  |mango             |    20       |light
+----+------------------+-------------+ 

我有以下尝试的脚本:

SELECT p.id,
       p.Name,
       Purchase.purchaseQty - sales.salseQty AS totalQty

FROM Product p
    OUTER APPLY (
        SELECT purchase.id,
               SUM(purchase.quantity) purchaseQty

        FROM purchase
        WHERE purchase.id = p.id
        GROUP BY
            purchase.id
) Purchase
     OUTER APPLY (
         SELECT sales.id,
                SUM(sales.quantity) salseQty
         FROM sales
         WHERE sales.id = p.id
         GROUP BY
             sales.id
) sales
;

1 个答案:

答案 0 :(得分:2)

这应该可以解决问题:

select P.id, Pr.product_name,
       case when S.quantity is null then P.quantity
            else P.quantity - S.quantity end as quantity,
       P.color from purchase as P
left join sales AS S on (P.id = S.id and P.color = S.color)
join product AS Pr on Pr.id = P.id