Search code examples
sqlmysqlmariadb

How to avoid calculating fields twice in mariadb view


I have following view in mariadb which gives stock credit, debit and balance :

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 

The problem is this part :

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

here the code is calculating balance but running the same calculation twice.

I have tried following 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

But mariadb throws an error 1351 saying

view contains variable or parameter which is not allowed

Is there any way to avoid calculating credit, debit twice for balance?


Solution

  • 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,
       (SELECT Credit - Debit) AS Bal,
       a.Desc1