How to SUM and SUBTRACT using SQL?

前端 未结 6 1454
甜味超标
甜味超标 2020-12-09 08:09

I am using MySQL and I have two tables:

master_table

  • ORDERNO
  • ITEM
  • QTY

stock_bal

6条回答
  •  孤街浪徒
    2020-12-09 08:18

    I have tried this kind of technique. Multiply the subtract from data by (-1) and then sum() the both amount then you will get subtracted amount.

    -- Loan Outstanding
        select  'Loan Outstanding' as Particular, sum(Unit), sum(UptoLastYear), sum(ThisYear), sum(UptoThisYear)
        from
        (
            select 
                sum(laod.dr) as Unit,
                sum(if(lao.created_at <= '2014-01-01',laod.dr,0)) as UptoLastYear,
                sum(if(lao.created_at between '2014-01-01' and '2015-07-14',laod.dr,0)) as ThisYear,
                sum(if(lao.created_at <= '2015-07-14',laod.dr,0)) as UptoThisYear
            from loan_account_opening as lao
            inner join loan_account_opening_detail as laod on lao.id=laod.loan_account_opening_id
            where lao.organization = 3
            union
            select
                sum(lr.installment)*-1 as Unit,
                sum(if(lr.created_at <= '2014-01-01',lr.installment,0))*-1 as UptoLastYear,
                sum(if(lr.created_at between '2014-01-01' and '2015-07-14',lr.installment,0))*-1 as ThisYear,
                sum(if(lr.created_at <= '2015-07-14',lr.installment,0))*-1 as UptoThisYear
            from loan_recovery as lr
            inner join loan_account_opening as lo on lr.loan_account_opening_id=lo.id
            where lo.organization = 3
        ) as t3
    

提交回复
热议问题