我使用的是 MS SQL Server,并且有 2 个表。
供应 list
sl_id(pk) supply_id(fk)* transaction_id Qty
1 14 872670099 3
2 15 872670100 5
3 16 872670101 1
4 16 872670105 4 <
- supply_id 是设施表中 Supply_id 的外键
供应
supply_id(pk) no_of_units
----------------------------
13 2
14 3
15 6
16 10
输出应该是supply_id,然后是no。可用单位数等于 No_of_units 减去数量。
输出
id units available
-------------------------
13 2
14 0 --> [1]
15 1
16 5 --> [2]
[1] 由于根据 Supply_list 表 Supply_id 14 的数量为 3
[2] 有两条记录包含 Supply_id 16,因此我们必须添加它们的数量,即 4 和 1,因此我们有 5 个。将从 Supply_id 16 的 no_of_units 中减去 5,我们将得到 5 个单位可用。
最佳答案
- 您将简单表的外部 JOIN 保留到父表
- 从父 no_of_units 值中减去列表数量值的总和
- 如果没有列表行,请使用 ISNULL
类似的东西
SELECT
S.supply_id,
S.no_of_units - ISNULL(SUM(SL.Qty), 0) AS [units available]
FROM
supply S
LEFT JOIN
supply_list SL ON S.supply_id = SL.supply_id
GROUP BY
S.supply_id, S.no_of_units
这使得聚合更加明显,但查询是相同的
SELECT
S.supply_id,
S.no_of_units - ISNULL(SL.SumListQty, 0) AS [units available]
FROM
supply S
LEFT JOIN
(
SELECT supply_id, SUM(Qty) AS SumListQty
FROM supply_list
GROUP BY supply_id
) SL ON S.supply_id = SL.supply_id
关于sql - SUM 聚合函数和子查询-SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6564724/