好的,伙计们关于这个话题的最后一个问题(我希望)。
我需要做的是对两个不同表中的字段求和,将它们加在一起,并检查这个总数是否大于客户的信用额度。
我已将我的问题分解为较小的任务,以便我可以尝试提出整体解决方案。(这些较小的代码对我来说可以正常工作,但是当在第三段代码中组合时,它们的总和不正确)。首先,我计算了第一个求和字段,如下所示:
--summmed open invoices
SELECT company, sum(unit_price * invoice_qty) as open_invoices
FROM
(SELECT arc.company, ard.unit_price, ard.invoice_qty, arc.credit_limit
FROM iqms.arprepost_detail ard, iqms.arprepost arp, iqms.arcusto arc
WHERE ard.arprepost_id = arp.ID
AND arp.arcusto_id = arc.ID)
GROUP BY company
ORDER BY company;
总结时,这里的数字是正确的,我已经手动检查过。接下来我总结了我需要的其他字段,如图所示:
--summed open orders
SELECT company, (sum (unit_price * total_qty_ord)) as total_open_orders
FROM
(SELECT arc.company, od.unit_price, od.total_qty_ord, arc.credit_limit
FROM iqms.arcusto arc, iqms.orders o, iqms.ord_detail od
WHERE od.orders_id = o.ID
AND o.arcusto_id = arc.ID
AND (od.cumm_shipped < od.total_qty_ord OR od.cumm_shipped IS NULL))
GROUP BY company
ORDER BY company;
这些数字再次在人工检查中正确显示。
我现在需要将这两个计算加在一起,并检查该数字是否大于该客户的“credit_limit”字段。我已经为此编写了代码,但数字超出了他们应该得到的结果(这段代码在下面给出)。
--summmed open invoices + open orders
SELECT company, credit_limit,
round(sum(i_up * invoice_qty)) AS total_invoices,
round(sum (o_up * total_qty_ord)) AS total_orders,
round(sum(i_up * invoice_qty) + sum (o_up * total_qty_ord)) as overall_total
FROM
(SELECT arc.company, arc.credit_limit, ard.unit_price as i_up, ard.invoice_qty, od.unit_price as o_up, od.total_qty_ord
FROM iqms.arprepost_detail ard, iqms.arprepost arp, iqms.arcusto arc, iqms.orders o, iqms.ord_detail od
WHERE
ard.arprepost_id = arp.ID
AND arp.arcusto_id = arc.ID
AND od.orders_id = o.ID
AND o.arcusto_id = arc.ID
AND (od.cumm_shipped < od.total_qty_ord OR od.cumm_shipped IS NULL)
)
GROUP BY company, credit_limit
HAVING ((sum(i_up * invoice_qty)) + (sum (o_up * total_qty_ord)) > credit_limit)
ORDER BY company;
我不确定我哪里出错了。也许这是一个简单的修复,或者我的逻辑有问题。非常感谢任何见解。非常感谢您一直以来的支持。