CREATE OR REPLACE FUNCTION get_order_count(customer_id IN NUMBER) RETURN NUMBER IS
order_count NUMBER;
BEGIN
SELECT COUNT(*) INTO order_count FROM orders WHERE customer_id = customer_id;
RETURN order_count;
END;
/
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
CREATE OR REPLACE PROCEDURE calculate_avg_order_count IS
cursor customer_cursor is
SELECT customer_id, get_order_count(customer_id) as order_count FROM customers;
total_order_count NUMBER := 0;
customer_count NUMBER := 0;
avg_order_count NUMBER := 0;
BEGIN
FOR customer_record IN customer_cursor LOOP
total_order_count := total_order_count + customer_record.order_count;
customer_count := customer_count + 1;
END LOOP;
IF customer_count > 0 THEN
avg_order_count := total_order_count / customer_count;
END IF;
dbms_output.put_line('Average order count: ' || avg_order_count);
END;
/
CREATE OR REPLACE PROCEDURE calculate_avg_order_count IS
cursor customer_cursor is
SELECT customer_id, get_order_count(customer_id) as order_count FROM customers;
total_order_count NUMBER := 0;
customer_count NUMBER := 0;
avg_order_count NUMBER := 0;
BEGIN
FOR customer_record IN customer_cursor LOOP
total_order_count := total_order_count + customer_record.order_count;
customer_count := customer_count + 1;
END LOOP;
IF customer_count > 0 THEN
avg_order_count := total_order_count / customer_count;
END IF;
INSERT INTO avg_order(customer_id, avg_order_count) VALUES (1, avg_order_count);
dbms_output.put_line('Average order count: ' || avg_order_count);
END;
/
CREATE OR REPLACE FUNCTION get_order_count(customer_id INTEGER) RETURNS INTEGER AS $$
SELECT COUNT(*) FROM orders WHERE customer_id = $1;
$$ LANGUAGE SQL;
這個函數會接收一個客戶ID,並回傳該客戶的訂單數量。
接下來,我們可以創建一個存儲過程,使用這個函數來計算每個客戶的平均訂單數量:
sql
CREATE OR REPLACE PROCEDURE calculate_avg_order_count() AS $$
DECLARE
customer_cursor CURSOR FOR SELECT customer_id, get_order_count(customer_id) as order_count FROM customers;
customer_record RECORD;
total_order_count INTEGER := 0;
customer_count INTEGER := 0;
avg_order_count NUMERIC := 0;
BEGIN
OPEN customer_cursor;
LOOP
FETCH customer_cursor INTO customer_record;
EXIT WHEN NOT FOUND;
total_order_count := total_order_count + customer_record.order_count;
customer_count := customer_count + 1;
END LOOP;
CLOSE customer_cursor;
IF customer_count > 0 THEN
avg_order_count := total_order_count / customer_count;
END IF;
INSERT INTO avg_order(customer_id, avg_order_count) VALUES (1, avg_order_count);
RAISE NOTICE 'Average order count: %', avg_order_count;
END;
$$ LANGUAGE plpgsql;