计算来自mycursor循环的总值之和

时间:2017-12-02 06:44:40

标签: sql oracle plsql

我不太确定如何计算所有项目的总计,我想找到每个项目的“总产品价值”的总和。我需要将其变为变量还是有其他方法可以做到这一点?

 /* DBMS_OUTPUT.PUT_LINE('Total product value: ' || (s_QtyExpected + s_QtyHand) 
    * s_ItemRate); */ 

-------
    DECLARE
    CURSOR myCursor IS SELECT Ship_ID, Date_Arrive, Qty_expected, Description, 
    Qty_Hand, Item_Rate
    FROM SampleData;
    s_ShipID NUMBER (5) := &shipID;
    s_DateArrival DATE;
    s_QtyExpected NUMBER (4);
    s_Description VARCHAR2 (20);
    s_QtyHand NUMBER (4);
    s_ItemRate NUMBER (6,3);
    BEGIN
    OPEN mycursor;
    LOOP
      FETCH mycursor INTO s_ShipID, s_DateArrival, s_QtyExpected, s_Description, 
    s_QtyHand, s_ItemRate;
      EXIT WHEN mycursor%NOTFOUND; 
     DBMS_OUTPUT.PUT_LINE('Shipment ' || s_ShipID || ' is expected to arrive on 
    ' || s_DateArrival || '.');
    DBMS_OUTPUT.PUT_LINE('Description: ' || s_Description);
    DBMS_OUTPUT.PUT_LINE('Shipment value: ' || s_QtyExpected * s_ItemRate);
    DBMS_OUTPUT.PUT_LINE('Quantity on Hand: ' || s_QtyHand);
    DBMS_OUTPUT.PUT_LINE('Total product value: ' || (s_QtyExpected + s_QtyHand) 
    * s_ItemRate);
    END LOOP;
    CLOSE myCursor;
    DBMS_OUTPUT.PUT_LINE('GRAND TOTAL VALUE OF ALL ITEMS:');
    END; 
    /

1 个答案:

答案 0 :(得分:0)

这正是Krokodillo写的。通常它是通过查询完成的。 然而,它也可以通过程序完成。 我想有多个记录,因为你使用循环。

如果" Qty_expected"和" Qty_Hand"取决于ship_Id您可以使用下一个查询:

select ship_id, sum((s_QtyExpected + s_QtyHand) * s_ItemRate)
from sampledata
group by ship_id;

或者您可以使用for循环(然后您不再需要"退出..."构造,因为当光标的最后一条记录被处理时,循环会自动停止。

declare
  CURSOR myCursor 
  IS 
  SELECT Ship_ID, Date_Arrive, Qty_expected, Description, 
         Qty_Hand, Item_Rate
  FROM SampleData;

  s_ShipID NUMBER (5) := &shipID;
  s_DateArrival DATE;
  s_QtyExpected NUMBER (4);
  s_Description VARCHAR2 (20);
  s_QtyHand NUMBER (4);
  s_ItemRate NUMBER (6,3);

  ln_grand_total    number;

BEGIN 

  for row in mycursor
  loop

    DBMS_OUTPUT.PUT_LINE('Shipment ' || row.s_ShipID || ' is expected to arrive on 
' || row.s_DateArrival || '.');
    DBMS_OUTPUT.PUT_LINE('Description: ' || row.s_Description);
    DBMS_OUTPUT.PUT_LINE('Shipment value: ' || row.s_QtyExpected * row.s_ItemRate);
    DBMS_OUTPUT.PUT_LINE('Quantity on Hand: ' || row.s_QtyHand);
    DBMS_OUTPUT.PUT_LINE('Total product value: ' || (row.s_QtyExpected + row.s_QtyHand) * row.s_ItemRate);

    ln_grand_total := ln_grand_total + (row.s_QtyExpected + row.s_QtyHand) * row.s_ItemRate;

  end loop;

  DBMS_OUTPUT.PUT_LINE('GRAND TOTAL VALUE OF ALL ITEMS:'||ln_grand_total);

end;

我希望这会对你有所帮助。