未找到SKU时返回0数量

时间:2018-06-13 16:23:23

标签: sql postgresql

我的数据库中有2个表:warehousewarehouse_inventory

我的warehouse表格如下:

 name   | warehouse_id   | 
--------+----------------|
 name_1 | warehouse_id_1 |
 name_2 | warehouse_id_2 |
 name_3 | warehouse_id_3 |

我的warehouse_inventory表格如下:

 warehouse_id   | SKU         | quantity |         
----------------+-------------+----------|
 warehouse_id_1 | item_sku_1  | 100      |
 warehouse_id_2 | item_sku_1  | 100      |

现在,我正在寻找一个能让我得到这样结果的解决方案:

 name   | warehouse_id   | SKU        | quantity |
--------+-----------------------------+----------|
 name_1 | warehouse_id_1 | item_sku_1 | 100      |
 name_1 | warehouse_id_1 | item_sku_2 | 0        |
 name_2 | warehouse_id_2 | item_sku_1 | 100      |
 name_2 | warehouse_id_2 | item_sku_2 | 0        |
 name_3 | warehouse_id_3 | item_sku_1 | 0        |
 name_3 | warehouse_id_3 | item_sku_2 | 0        |

当我在SQL查询中选择where条件时:

SELECT * FROM [what's here?] WHERE warehouse_inventory.SKU IN ('item_sku_1', 'item_sku_2')

2 个答案:

答案 0 :(得分:0)

如果您没有包含数据库中所有SKU的表格,则无法执行此操作。

因此,假设您的所有商品主数据都有一个名为[item]的表,那么您应该这样做:

SELECT W0.name, W0.warehouse_id, I0.SKU, ISNULL(W1.quatity, 0) as 'Quantity'
FROM [item] I0
CROSS JOIN [warehouse] W0
LEFT JOIN [warehouse_inventory] W1 ON W1.warehouse_id = W0.warehouse_id AND W1.SKU = I0.SKU

在SAP Business One上,我们这样做:

SELECT W0.WhsName, W0.WhsCode, I0.ItemCode, ISNULL(W1.OnHand, 0) as 'Quantity'
FROM OITM I0
CROSS JOIN OWHS W0
LEFT JOIN OITW W1 ON W1.WhsCode = W0.WhsCode AND W1.ItemCode = I0.ItemCode
ORDER BY 1 DESC

答案 1 :(得分:0)

您可以将CROSS JOINLEFT JOIN

一起使用
select w.name, w.warehouse_id, wii.SKU, coalesce(i.quantity, 0) as quantity 
from warehouse w cross join 
     warehouse_inventory wii left join
     warehouse_inventory i 
     on i.warehouse_id = w.warehouse_id and i.SKU = wii.SKU
order by w.name;