source: database/Advanced Reports for database/Stores ordered by total revenue in the last calendar year from highest to lowest.txt@ 6149556

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

Project Handcraft Marketplace

  • Property mode set to 100644
File size: 1.2 KB
Line 
1CREATE OR REPLACE FUNCTION get_stores_by_last_calendar_year_revenue()
2RETURNS TABLE (
3 store_id INT,
4 store_name TEXT,
5 number_of_orders BIGINT,
6 total_quantity_sold BIGINT,
7 total_revenue NUMERIC
8)
9LANGUAGE plpgsql
10AS $$
11BEGIN
12 RETURN QUERY
13 SELECT
14 s.store_id,
15 s.name AS store_name,
16 COUNT(DISTINCT o.order_num) AS number_of_orders,
17 COALESCE(SUM(o.quantity), 0) AS total_quantity_sold,
18 COALESCE(
19 SUM(
20 p.price
21 * o.quantity
22 * (1 - COALESCE(o.discount, 0) / 100.0)
23 ),
24 0
25 ) AS total_revenue
26 FROM store s
27 LEFT JOIN sells se
28 ON s.store_id = se.store_id
29 LEFT JOIN product p
30 ON se.code = p.code
31 LEFT JOIN includes i
32 ON p.code = i.code
33 LEFT JOIN "order" o
34 ON i.order_num = o.order_num
35 AND o.last_modified_date >= DATE_TRUNC(
36 'year',
37 CURRENT_DATE
38 ) - INTERVAL '1 year'
39 AND o.last_modified_date < DATE_TRUNC(
40 'year',
41 CURRENT_DATE
42 )
43 GROUP BY
44 s.store_id,
45 s.name
46 ORDER BY
47 total_revenue DESC;
48END;
49$$;
Note: See TracBrowser for help on using the repository browser.