source: database/Advanced Reports for database/Each product's monthly sales.txt@ 06ebe74

finki-main main
Last change on this file since 06ebe74 was 62b2964, checked in by Klimentina Efremova <klimentina08642@…>, 2 weeks ago

Project Handcraft Marketplace

  • Property mode set to 100644
File size: 1.1 KB
Line 
1CREATE OR REPLACE FUNCTION get_products_monthly_sales()
2RETURNS TABLE (
3 product_code INT,
4 product_description TEXT,
5 year INT,
6 month INT,
7 number_of_orders BIGINT,
8 total_quantity_sold 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 EXTRACT(YEAR FROM o.last_modified_date)::INT AS year,
19 EXTRACT(MONTH FROM o.last_modified_date)::INT AS month,
20 COUNT(DISTINCT o.order_num) AS number_of_orders,
21 SUM(o.quantity) AS total_quantity_sold,
22 SUM(
23 p.price
24 * o.quantity
25 * (1 - COALESCE(o.discount, 0) / 100.0)
26 ) AS total_revenue
27 FROM product p
28 JOIN includes i
29 ON p.code = i.code
30 JOIN "order" o
31 ON i.order_num = o.order_num
32 GROUP BY
33 p.code,
34 p.description,
35 EXTRACT(YEAR FROM o.last_modified_date),
36 EXTRACT(MONTH FROM o.last_modified_date)
37 ORDER BY
38 year DESC,
39 month DESC,
40 total_revenue DESC;
41END;
42$$;
Note: See TracBrowser for help on using the repository browser.