您可以在outer query
不alias
生成相同查询的情况下执行此操作.
SELECT items_no, item_desc, item_qty, grn_qty, issues_qty, total_qty = grn_qty + issues_qty FROM (SELECT s.items_no, s.item_desc, s.item_qty, (SELECT Isnull(Sum(g.qty), 0) FROM grn_details g WHERE g.items_no = s.items_no) grn_qty, (SELECT Isnull(Sum(i.qty), 0) FROM stk_issue_details i WHERE i.items_no = s.items_no) issues_qty FROM stocks s) a
或者你可以使用OUTER APPLY
只select
需要单身的地方
SELECT s.items_no, s.item_desc, s.item_qty, grn_qty, issues_qty, total_qty = grn_qty + issues_qty FROM stocks s OUTER apply (SELECT Isnull(Sum(g.qty), 0) FROM grn_details g WHERE g.items_no = s.items_no) g(grn_qty) OUTER apply (SELECT Isnull(Sum(i.qty), 0) FROM stk_issue_details i WHERE i.items_no = s.items_no) i (issues_qty)