我正在使用MS SQL Server,我有2个表。
Supply_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(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.而且5将从supply_id 16的no_of_units中减去,我们将获得5个单位可用。
答案 0 :(得分:3)
像
这样的东西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