IBM SQL总和和分组依据

时间:2019-03-21 12:32:01

标签: sql db2 ibm-midrange

我正在尝试加入并获取采购订单中订单项的总数(总和)。它是网页上的网格。我正在显示采购订单的所有信息,但我还希望每个采购订单的每个订单项的总金额。

我收到以下错误消息:

SQL0122 SELECT列表中的列或表达式无效。

我不确定自己在做什么错吗?

表格:

表@HPO(PO):

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

表HPO(PO中的行项目):

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

表AVM(供应商):

Vendor Vendor#
aaa     444
bbb     555
ccc     777 

这是我的代码:

    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;    

1 个答案:

答案 0 :(得分:3)

在选择列表中以及在group by子句中指定列名

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

根据您的代码-从group by删除C.PECST

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