从2个表中求和并将它相互减去

时间:2015-10-24 09:13:20

标签: sql-server

我有2个表,ord_tbl和pay_tbl。 o_tbl包含这些数据。

ord_tbl

invoice | emp_id | prod_id | amount
123     | 101    | 1       | 1000
123     | 101    | 2       | 500
123     | 101    | 3       | 500
124     | 101    | 2       | 300
125     | 102    | 3       | 200

pay_tbl

invoice | new_invoice | amount
123     | 321         | 300
123     | 322         | 200
124     | 323         | 300
125     | 324         | 100

我想选择陈述给我这个结果

invoice | emp_id | orig_amt | balance | status
123     | 101    | 2000     | 1500    | unsettled

将不再包含余额为0的发票。我知道我必须在这里使用join和sub查询,但我甚至不知道如何启动它!对我来说,作为初学者,这已经非常复杂了。这是我到目前为止所尝试的......

SELECT 
  ord_tbl.invoice,
  SUM(ord_tbl.amount) As 'origAmt',
  SUM(pay_tbl.amount) As 'payAmt', 
  origAmt - payAmt As 'bal' 
FROM 
  ord_tbl 
  INNER JOIN pay_tbl 
    ON ord_tbl.invoice = pay_tbl.invoice 
WHERE 
  ord_tbl.emp_id = @emp_id AND 
  bal != 0 
GROUP BY 
  ord_tbl.invoice

1 个答案:

答案 0 :(得分:1)

你需要准备你的数据加入非唯一字段会导致交叉加入,这就是为什么你得到4000

;WITH CTE as
(SELECT ot.invoice,MAX(ot.emp_id) as emp_id,SUM(ot.amount) as origAmt FROM ord_tbl ot GROUP BY ot.invoice),
CTE2 as
( SELECT pt.invoice,SUM(pt.ammount) as payAmt FROM pay_tbl pt GROUP BY pt.invoice)
SELECT CTE.invoice,CTE.emp_id,CTE.origAmt,CTE.origAmt-NULLIF(CTE2.payAmt,0) as bal,'unsettled' as status
FROM
CTE LEFT JOIN CTE2 ON CTE.invoice=CTE2.invoice 
AND CTE.emp_id=101 AND CTE.origAmt-NULLIF(CTE2.payAmt,0)>0