DB2 Select 来自两个 table,而一个 table 需要总和
DB2 Select from two tables when one table requires sum
在 DB2 数据库中,我想使用 SQL 查询进行以下简单数学运算:
AvailableStock = SupplyStock - DemandStock
SupplyStock 存储在 1 table 的 1 行中,我们称此 table 为 Supply table。
所以 Supply table 有这个数据:
ProductID | SupplyStock
---------------------
109 10
244 7 edit: exclude this product from the search
DemandStock 存储在单独的 table 需求中,其中记录需求,因为每个客户在客户订单旅程中记录需求。来自需求的示例数据 table:
ProductID | DemandStock
------------------------
109 1
244 4 edit: exclude this product
109 6
109 2
所以在我们的头脑中,如果我想计算产品“109”的可用库存,供应为 10,产品 109 的需求总计为 9,因此可用库存为 1。
如何在 DB2 SQL 中的 一个 select 查询 中执行此操作?
到目前为止我对伪代码中的一些想象步骤的了解:
- I select SupplyStock,其中产品 ID = '109'
- I select sum(DemandStock) 其中产品 ID = '109'
- 我从 DemandStock 中减去 SupplyStock
- 我将其作为结果 AvailableStock 呈现
结果将如下所示:
Product ID | AvailableStock
109 9
我很想在一个 SQL select 查询中得到这个 selected。
编辑: 我已经收到了一个答案(几乎是完美的)并且意识到这个问题遗漏了一些信息。
这条信息:
我们需要从我们不想 select 数据的产品中排除数据,我们还需要专门 select 产品 109。
抱歉,原始问题中省略了这一点。
我已将 'where' 添加到 select 产品,这对我有用。但为了将来,也许答案也应该包括这些信息。
您可以使用 join
将表放在一起并使用 group by
聚合 join
:
的结果
select s.ProductId, s.SupplyStock, sum(d.DemandStock),
(s.SupplyStock - sum(d.DemandStock)) as Available
from Supply s left join
Demand d
on s.ProductId = d.ProductId
where s.ProductId = 109
group by s.ProductId, s.SupplyStock;
在 DB2 数据库中,我想使用 SQL 查询进行以下简单数学运算:
AvailableStock = SupplyStock - DemandStock
SupplyStock 存储在 1 table 的 1 行中,我们称此 table 为 Supply table。 所以 Supply table 有这个数据:
ProductID | SupplyStock
---------------------
109 10
244 7 edit: exclude this product from the search
DemandStock 存储在单独的 table 需求中,其中记录需求,因为每个客户在客户订单旅程中记录需求。来自需求的示例数据 table:
ProductID | DemandStock
------------------------
109 1
244 4 edit: exclude this product
109 6
109 2
所以在我们的头脑中,如果我想计算产品“109”的可用库存,供应为 10,产品 109 的需求总计为 9,因此可用库存为 1。
如何在 DB2 SQL 中的 一个 select 查询 中执行此操作?
到目前为止我对伪代码中的一些想象步骤的了解:
- I select SupplyStock,其中产品 ID = '109'
- I select sum(DemandStock) 其中产品 ID = '109'
- 我从 DemandStock 中减去 SupplyStock
- 我将其作为结果 AvailableStock 呈现
结果将如下所示:
Product ID | AvailableStock
109 9
我很想在一个 SQL select 查询中得到这个 selected。
编辑: 我已经收到了一个答案(几乎是完美的)并且意识到这个问题遗漏了一些信息。 这条信息: 我们需要从我们不想 select 数据的产品中排除数据,我们还需要专门 select 产品 109。 抱歉,原始问题中省略了这一点。 我已将 'where' 添加到 select 产品,这对我有用。但为了将来,也许答案也应该包括这些信息。
您可以使用 join
将表放在一起并使用 group by
聚合 join
:
select s.ProductId, s.SupplyStock, sum(d.DemandStock),
(s.SupplyStock - sum(d.DemandStock)) as Available
from Supply s left join
Demand d
on s.ProductId = d.ProductId
where s.ProductId = 109
group by s.ProductId, s.SupplyStock;