我有两张桌子
Master
Detail
在Master&细节表,我有一个Amount
字段
我需要获得Amount的详细信息并从Master中减去Amount并显示在“Current_Amount”中
“Current_Amount”应该等于“Master.Amount” - “Detail.Amount”的总和
答案 0 :(得分:3)
如果两张桌子上没有大量细节,这将为您提供总数:
SELECT (Max(M.Amount) - SUM(D.Amount)) as CurrentAmount
FROM Master M
INNER JOIN Detail D
ON M.ID = D.ID
然后,如果你想要包括主Id:
SELECT M.ID, (Max(M.Amount) - SUM(D.Amount)) as CurrentAmount
FROM Master M
INNER JOIN Detail D
ON M.ID = D.ID
GROUP BY M.ID
答案 1 :(得分:1)
尝试:
select m.ID, max(m.Amount) - sum(d.Ammount) Current_Amount
from Master m
left join Detail D on m.ID = d.Master_ID
group by m.ID
- 假设Master主键ID存储在Detail作为Master_ID。
答案 2 :(得分:1)
由于您没有指定...
,因此会对连接条件进行假设SELECT Master.ID,
(MAX(Master.Amount) - ISNULL(SUM(Detail.Amount), 0)) AS Current_Amount
FROM Master
LEFT JOIN Detail ON Detail.MasterID = Master.ID
GROUP BY Master.ID
注意: MAX(Master.Amount)
只是无需在group by子句中指定Master.Amount
。