找到每个客户的订单数量

时间:2014-04-16 02:06:41

标签: oracle plsql cursor

我试图将每个客户的订单数量显示为dbms_output.put_line,但计数不正确...我做错了什么?

declare
  t_order       number;
  cust_id       customer.c_id%type;
  orders_cid    orders.c_id%type;
  cust_first    customer.c_first%type;
  cust_last customer.c_last%type;

  cursor c is
    select distinct(customer.c_id),
           customer.c_first,
           customer.c_last,
           orders.c_id
      from customer
      join orders
        on customer.c_id = orders.c_id;
begin
  dbms_output.put_line('AZ SPORTS OUTSTANDING ORDERS');
  dbms_output.put_line('FIRST   LAST    TOTAL');
  dbms_output.put_line('NAME    NAME    ORDERS');

  OPEN C;
  LOOP
    FETCH C INTO CUST_ID, CUST_FIRST, CUST_LAST, ORDERS_CID;
    EXIT WHEN C%NOTFOUND;

    IF CUST_ID=ORDERS_CID THEN
      select count(distinct(orders.c_id))
        into t_order
        from orders
        join customer
          on orders.c_id = customer.c_id

      DBMS_OUTPUT.PUT_LINE(TO_CHAR(CUST_FIRST) || ' ' ||
                           TO_CHAR(CUST_LAST)  || ' ' ||
                           TO_CHAR(T_ORDER));
    END IF;
  END LOOP;

  CLOSE C;
END;
/

每个客户的订单数量一直显示为每个客户5,这不是正确的答案。

1 个答案:

答案 0 :(得分:0)

在我看来,您需要在SELECT COUNT...语句中使用WHERE子句 - 可能类似于WHERE ORDERS.C_ID = ORDERS_CID AND CUSTOMER.C_ID = CUST_ID。试试看,看看它是如何运作的。

分享并享受。