从2个表中总结列值并获得它们的差异

时间:2015-10-28 00:44:03

标签: ms-access ms-access-2010

我有2个表,ord_tbl和pay_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的发票。这是我到目前为止所尝试的......

;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.amountt) as payAmt FROM pay_tbl GROUP BY pt.invoice)
SELECT CTE.invoice, CTE.emp_id, CTE.origAmt, CTE.origAmt-CTE2.payAmt as bal, 'UNSETTLED' as status
FROM
CTE LEFT JOIN CTE2 ON CTE.invoice=CTE2.invoice
WHERE CTE.emp_id='101' AND CTE.origAmt-CTE2.payAmt>0 OR CTE2.patAmt IS NULL

这是我在这里教过的,它可以在sql server中使用。我现在需要的是在ms访问中运行它。我尝试了这段代码,但ms访问给我一个错误,说“无效的SQL语句;预期'删除','插入','选择'或'更新'。” 你能帮我吗?感谢。

2 个答案:

答案 0 :(得分:1)

MS ACCESS sql很差,ACCESS不知道WITH指令。我创建了表(所有字段都是int类型)。我重写了查询,这个查询有效:

SELECT CTE.invoiceCTE, 
       CTE.emp_idCTE, 
       CTE.origAmtCTE, 
       CTE.origAmtCTE-CTE2.payAmtCTE2 as bal, 
        'UNSETTLED' as status
FROM 
 (SELECT invoice as invoiceCTE, 
  MAX(emp_id) as emp_idCTE, 
  SUM(amount) as origAmtCTE 
  FROM ord_tbl 
  GROUP BY invoice) as CTE
LEFT JOIN 
( SELECT invoice as invoiceCTE2, 
  SUM(amount) as payAmtCTE2
   FROM pay_tbl 
  GROUP BY invoice) as CTE2
ON CTE.invoiceCTE=CTE2.invoiceCTE2
WHERE CTE.emp_idCTE=101
    AND (CTE.origAmtCTE-CTE2.payAmtCTE2>0 OR CTE2.payAmtCTE2 IS NULL)

答案 1 :(得分:0)

我不知道emp_id。如果是某种客户ID,则每个invoice_id只有一个,并且您需要此SQL:

SELECT 
  ord_tbl.invoice, 
  First(ord_tbl.emp_id) AS ErsterWertvonemp_id, 
  Sum(ord_tbl.amount) AS origAmt, 
  Sum([ord_tbl].[amount])-Sum([pay_tbl].[amount]) AS bal, 
  "unsettled" AS status
FROM 
  ord_tbl LEFT JOIN pay_tbl 
  ON ord_tbl.invoice = pay_tbl.invoice
GROUP BY ord_tbl.invoice
HAVING (((Sum([ord_tbl].[amount])-Sum([pay_tbl].[amount]))>0));

如果您只想选择emp_id = 101的那个,您需要这样:

SELECT 
   ord_tbl.invoice, 
   ord_tbl.emp_id, 
   Sum(ord_tbl.amount) AS origAmt, 
   Sum([ord_tbl].[amount])-Sum([pay_tbl].[amount]) AS bal, 
   "unsettled" AS status
FROM 
   ord_tbl LEFT JOIN pay_tbl 
   ON ord_tbl.invoice = pay_tbl.invoice
GROUP BY 
   ord_tbl.invoice, 
   ord_tbl.emp_id
HAVING (
   ((ord_tbl.emp_id)=101) 
   AND 
   ((Sum([ord_tbl].[amount])-Sum([pay_tbl].[amount]))>0)
);