= List of most popular products with total number of sales {{{#!sql CREATE OR REPLACE FUNCTION get_products_by_total_sales() RETURNS TABLE ( product_code INT, product_description TEXT, product_price NUMERIC, number_of_orders BIGINT, total_revenue NUMERIC ) LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT p.code AS product_code, p.description AS product_description, p.price AS product_price, COUNT(DISTINCT o.order_num) AS number_of_orders, COALESCE( SUM( p.price * o.quantity * (1 - COALESCE(o.discount, 0) / 100.0) ), 0 ) AS total_revenue FROM product p LEFT JOIN includes i ON p.code = i.code LEFT JOIN "order" o ON i.order_num = o.order_num GROUP BY p.code, p.description, p.price ORDER BY number_of_orders DESC, total_revenue DESC; END; $$; }}} == Relational Algebra - P(code, price, availability, description, ...) - O(order_num, quantity, status, last_modified_date, payment_method, discount) - I(code, order_num) **JOIN products with orders:** - J1 ← P ⟕P.code = I.code I - J2 ← J1 ⟕I.order_num = O.order_num O **Calculate revenue from product for each order:** - **FORMULA:** order_total = Σ(P.price × O.quantity) × (1 - COALESCE(O.discount, 0) / 100) - OR ← πcode, description, price, order_num, quantity, discount, price × quantity × (1 - COALESCE(discount, 0) / 100) → order_revenue(J2) * OR = order revenue **Calculate total number of orders the product has been in and total revenue:** - R ← γcode, description, price; COUNT(DISTINCT order_num) → number_of_orders, Σ(order_revenue) → total_revenue (OR) - For products that have never been ordered: - number_of_orders = 0 - total_revenue = 0 **Sort by order total:** - R_final ← τnumber_of_orders DESC, total_revenue DESC(R)