如何避免在 mariadb 视图中两次计算字段
有以下观点,其中给出了股票贷方、借方和余额:mariadb
SELECT pitem,
Bdate,
credit,
debit,
sum(ifnull(bal, 0)) OVER (PARTITION BY pitem ORDER BY bdate, DESC1) balance,
DESC1
FROM (
SELECT a.Pitem,
a.Bdate,
a.Trn,
If((trn=1 AND a.qty>0), a.Qty, 0) AS Credit,
If(trn=0 OR a.qty<0, abs(a.Qty), 0) AS Debit,
(If((trn=1 AND a.qty>0), a.Qty, 0)) - (If(trn=0 OR a.qty<0, abs(a.Qty), 0)) AS Bal,
a.Desc1
FROM (
SELECT tblphmrefill.RfItem AS PItem,
tblphmrefill.rfDate AS BDate,
tblphmrefill.rfQty AS Qty,
CONCAT(
if(rfqty>0, 'Purchase No_', 'Discard_BMW_'),
coalesce(tblphmrefill.RfInvoice, 0), '_Vend_', rfsuppID
) AS DESC1,
1 AS Trn
FROM tblphmrefill
UNION (
SELECT invoicerefundphm.phmItem AS pItem,
invoice.Bdate,
invoicerefundphm.Qty,
CONCAT('Refund_', billno, '_', invoice.BName) AS DESC1,
1 AS Trn
FROM invoice
)
INNER JOIN invoicerefundphm
ON invoice.BilID = invoicerefundphm.Billno
UNION (
SELECT invoicephm.phmItem AS PItem,
invoice.BDate,
invoicephm.Qty,
CONCAT('Sales_', billno, '_', invoice.BName),
0 AS Trn
FROM invoicephm
INNER JOIN invoice
ON invoicephm.Billno = invoice.BilID
ORDER BY invoice.bdate, invoice.bilid ASC
)
) AS a
) phmtbatch_int
Order by Bdate, DESC1 Asc
问题是这部分:
SELECT a.Pitem,
a.Bdate,
a.Trn,
If((trn=1 AND a.qty>0), a.Qty, 0) AS Credit,
If(trn=0 OR a.qty<0, abs(a.Qty), 0) AS Debit,
(If((trn=1 AND a.qty>0), a.Qty, 0)) - (If(trn=0 OR a.qty<0, abs(a.Qty), 0)) AS Bal,
a.Desc1
此处的代码正在计算余额,但运行相同的计算两次。
我尝试了以下 thinng:
SELECT a.Pitem,
a.Bdate,
a.Trn,
@Credit := (If((trn=1 AND a.qty>0), a.Qty, 0)) AS Credit,
@Debit := (If(trn=0 OR a.qty<0, abs(a.Qty), 0)) AS Debit,
(@Credit - @Debit) AS Bal,
a.Desc1
但 mariadb 抛出了一句话error 1351
view contains variable or parameter which is not allowed
有什么方法可以避免计算贷方,为余额借记两次?