编写一个PL / SQL块,它将填充RESULTS表,如下所述:

时间:2015-06-14 18:17:04

标签: database oracle performance plsql

我需要在每个客户ID和数量中插入RESULTS表 该客户购买的独特产品。其次,我需要将客户表的最近购买列更新为“Y”(如果他们在过去12个月内购买了产品,则为是)或“N”(如果他们在过去12个月内未购买产品)。

下面列出的是表&定义:

table: CUSTOMER
columns: customer_id NUMBER, customer_name VARCHAR2(100), recently_purchased VARCHAR2(1) -- 'Y' or 'N'

table: CUST_PRODUCTS
columns: product_id NUMBER, customer_id NUMBER, date_purchased DATE

table: RESULTS
columns: customer_id NUMBER, product_count NUMBER

table: PRODUCTS
column: product_id NUMBER, product_name VARCHAR2(100)

这就是我的想法:

DECLARE

GET_DATE DATE;

BEGIN

INSERT INTO RESULTS (customer_id, product_count)
SELECT c.customer_id, (select count(product_id) 
                    from CUST_PRODUCTS p 
                    where p.customer_id = c.customer_id)
FROM CUST_PRODUCTS c);

SELECT  date_purchased 
INTO  GET_DATE
FROM CUST_PRODUCTS;
IF GET_DATE < SYSDATE - 365
    UPDATE customer
    SET recently_purchased =  "Y";
ELSE 
    UPDATE customer
    SET recently_purchased =  "N";
END IF;  
END

请帮忙核实一下。我没有任何数据库软件来测试我的代码。感谢

1 个答案:

答案 0 :(得分:0)

    DECLARE
        GET_DATE DATE;
        GET_ID Number;  

    CURSOR c1
       IS
         SELECT date_purchased, customer_id
         FROM CUST_PRODUCTS
         WHERE date_purchased < SYSDATE;

    BEGIN
        INSERT INTO RESULTS (customer_id, product_count)
        SELECT c.customer_id,(SELECT count(DISTINCT P.product_id) 
        FROM CUST_PRODUCTS P
        WHERE P.customer_id = C.customer_id)
        FROM CUSTOMER C;

        OPEN c1;
        LOOP
         FETCH c1 INTO GET_DATE, GET_ID;
         IF GET_DATE > SYSDATE-365 THEN
            UPDATE CUSTOMER
            SET recently_purchased =  'Y'
            WHERE customer_id = GET_ID;
       ELSE
          UPDATE CUSTOMER
            SET recently_purchased =  'N'
            WHERE customer_id = GET_ID;

       END IF;
         EXIT WHEN c1%NOTFOUND;
        END LOOP;   

       CLOSE c1;

    END;
    //