Search code examples
sqldb2ibm-midrange

IBM SQL Sum and Group By


I am trying to do a join and get the total (sum) of Line Items in Purchase orders. It is a grid on a web page. I am displaying all the info of the PO but I also want the Total dollar per line items per PO's.

I get the following error message:

SQL0122 Column or expression in SELECT list not valid.

I am not sure what I am doing wrong?

Tables:

Table @HPO (PO):

PO#   Vendor  Status
123   aaa     Approved
321   bbb     Approved
456   ccc     Pending
654   ddd     Draft  

Table HPO (line Items in PO):

PO#  Total Price
123  100.00
123  25.00
321  75.00
456  25.00
654  10.00
654  90.00

Table AVM (Vendor):

Vendor Vendor#
aaa     444
bbb     555
ccc     777 

Here is my code:

    EXEC SQL Declare RSCURSOR1 cursor for
          SELECT A.*, B.*, SUM(C.PECST) as POTOTAL
          FROM @HPO A
          INNER JOIN AVM B on A.HPOVNO = B.VENDOR
          INNER JOIN HPO C on A.HPOORD = C.PORD
          GROUP BY C.PORD
          ORDER BY HPOORD DESC

          OFFSET (:StartingRow - 1) * :NbrOfRows ROWS
          FETCH NEXT :NbrOfRows + 1 ROWS ONLY;

          EXEC SQL  Open RSCURSOR1;

          EXEC SQL SET RESULT SETS Cursor RSCURSOR1;  

Update code:

EXEC SQL Declare RSCURSOR1 cursor for
      SELECT A.HPOORD, A.HPORNB, A.HPORBY, A.HPODTO, A.HPOSTS, A.HPOVNO, A.HPOURG, B.VNDNAM, SUM(C.PECST) as POTOTAL
      FROM @HPO A
      INNER JOIN AVM B on A.HPOVNO = B.VENDOR
      INNER JOIN HPO C on A.HPOORD = C.PORD
      GROUP BY A.HPOORD, A.HPORNB, A.HPORBY, A.HPODTO, A.HPOSTS, A.HPOVNO, A.HPOURG, B.VNDNAM, C.PECST
      ORDER BY HPOORD DESC

      OFFSET (:StartingRow - 1) * :NbrOfRows ROWS
      FETCH NEXT :NbrOfRows + 1 ROWS ONLY;

      EXEC SQL  Open RSCURSOR1;

      EXEC SQL SET RESULT SETS Cursor RSCURSOR1;    

Solution

  • specify column names in select list as well as in group by clause

    DEMO

    SELECT A.PO#,Vendor,Status, SUM(C.PECST) as POTOTAL
          FROM @HPO A
          INNER JOIN AVM B on A.HPOVNO = B.VENDOR
          INNER JOIN HPO C on A.HPOORD = C.PORD
          GROUP BY A.PO#,Vendor,Status
          ORDER BY HPOORD DESC
    

    AS per your code - remove C.PECST from group by

    SELECT A.HPOORD, A.HPORNB, A.HPORBY, A.HPODTO, A.HPOSTS, A.HPOVNO, A.HPOURG, B.VNDNAM, SUM(C.PECST) as POTOTAL
          FROM @HPO A
          INNER JOIN AVM B on A.HPOVNO = B.VENDOR
          INNER JOIN HPO C on A.HPOORD = C.PORD
          GROUP BY A.HPOORD, A.HPORNB, A.HPORBY, A.HPODTO, A.HPOSTS, A.HPOVNO, A.HPOURG, B.VNDNAM
          ORDER BY HPOORD DESC