Changes between Initial Version and Version 1 of AdvancedReport2


Ignore:
Timestamp:
08/21/26 05:27:15 (30 hours ago)
Author:
235018
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • AdvancedReport2

    v1 v1  
     1= List of most popular products with total number of sales
     2{{{#!sql
     3CREATE OR REPLACE FUNCTION get_products_by_total_sales()
     4RETURNS TABLE (
     5    product_code INT,
     6    product_description TEXT,
     7    product_price NUMERIC,
     8    number_of_orders BIGINT,
     9    total_revenue NUMERIC
     10)
     11LANGUAGE plpgsql
     12AS $$
     13BEGIN
     14    RETURN QUERY
     15    SELECT
     16        p.code AS product_code,
     17        p.description AS product_description,
     18        p.price AS product_price,
     19        COUNT(DISTINCT o.order_num) AS number_of_orders,
     20        COALESCE(
     21            SUM(
     22                p.price
     23                * o.quantity
     24                * (1 - COALESCE(o.discount, 0) / 100.0)
     25            ),
     26            0
     27        ) AS total_revenue
     28    FROM product p
     29    LEFT JOIN includes i
     30        ON p.code = i.code
     31    LEFT JOIN "order" o
     32        ON i.order_num = o.order_num
     33    GROUP BY
     34        p.code,
     35        p.description,
     36        p.price
     37    ORDER BY
     38        number_of_orders DESC,
     39        total_revenue DESC;
     40END;
     41$$;
     42
     43}}}
     44
     45== Relational Algebra
     46- P(code, price, availability, description, ...)
     47- O(order_num, quantity, status, last_modified_date, payment_method, discount)
     48- I(code, order_num)
     49
     50**JOIN products with orders:**
     51- J1 ← P ⟕P.code = I.code I
     52- J2 ← J1 ⟕I.order_num = O.order_num O
     53
     54**Calculate revenue from product for each order:**
     55- **FORMULA:** order_total = Σ(P.price × O.quantity) × (1 - COALESCE(O.discount, 0) / 100)
     56
     57- OR ← πcode, description, price, order_num, quantity, discount,
     58      price × quantity ×
     59      (1 - COALESCE(discount, 0) / 100)
     60      → order_revenue(J2)
     61
     62* OR = order revenue
     63
     64**Calculate total number of orders the product has been in and total revenue:**
     65- R ← γcode, description, price;
     66     COUNT(DISTINCT order_num) → number_of_orders,
     67     Σ(order_revenue) → total_revenue
     68     (OR)
     69- For products that have never been ordered:
     70    - number_of_orders = 0
     71    - total_revenue = 0
     72
     73**Sort by order total:**
     74- R_final ← τnumber_of_orders DESC, total_revenue DESC(R)
     75
     76