sqlmysqlconditional-statements

select columns base on different conditions in mysql php


I need help for this code. What did I do wrong. I want a result that give me group by Commercial, Residential and Agriculture basic column amount in current and previous revperiod column. How to accomplish with this code or better any suggestion about it. Thank you in advance.

SELECT  (CASE (c.classcode)
         WHEN 'C' THEN 'COMMERCIAL'
         WHEN 'R' THEN 'RESIDENTIAL'
         WHEN 'A' THEN 'AGRICULTURE' END) AS CLASSIFICATION,
        ( SELECT  SUM(a.basic)
            FROM  cashreceiptitem_rpt_online a
            JOIN  cashreceipt_rpt b  ON a.rptreceiptid=b.objid
            JOIN  rptledger c  ON a.rptledgerid=c.objid
            WHERE  b.month='11'
              AND  a.revperiod='current'
        ) AS BC, 
        ( SELECT  SUM(a.basic)
            FROM  cashreceiptitem_rpt_online a
            JOIN  cashreceipt_rpt b  ON a.rptreceiptid=b.objid
            JOIN  rptledger c  ON a.rptledgerid=c.objid
            WHERE  b.month='11'
              AND  a.revperiod='previous'
        ) AS BPC
    FROM  cashreceiptitem_rpt_online a
    JOIN  cashreceipt_rpt b  ON a.rptreceiptid=b.objid
    JOIN  rptledger c  ON a.rptledgerid=c.objid
    WHERE  b.month='11'

I have this error Error Code: 1242; Subquery returns more than 1 row.


Solution

  • Not sure about your table structure but you should be able to do something like this:

    SELECT c.classcode, SUM(a.basic), SUM(aprev.basic)
    FROM cashreceiptitem_rpt_online a
    JOIN cashreceiptitem_rpt_online aprev 
        ON a.rptreceiptid = aprev.rptreceiptid
    JOIN cashreceipt_rpt b ON a.rptreceiptid=b.objid
    JOIN cashreceipt_rpt bprev ON a.rptreceiptid=bprev.objid
    JOIN rptledger c ON a.rptledgerid=c.objid
    WHERE b.month='11' AND bprev.month='11'
    AND a.revperiod='current' AND aprev.revperiod = 'previous'
    GROUP BY c.classcode;
    

    You'll need to figure out appropriate joins for your table's primary keys.