source: database/Advanced Reports for database/Store with highest revenue growth in the last calendar year.txt@ 6149556

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

Project Handcraft Marketplace

  • Property mode set to 100644
File size: 2.0 KB
RevLine 
[62b2964]1CREATE OR REPLACE FUNCTION get_store_with_highest_revenue_growth()
2RETURNS TABLE (
3 store_id INT,
4 store_name TEXT,
5 previous_year_revenue NUMERIC,
6 last_year_revenue NUMERIC,
7 revenue_growth NUMERIC
8)
9LANGUAGE plpgsql
10AS $$
11BEGIN
12 RETURN QUERY
13 WITH yearly_revenue AS (
14 SELECT
15 s.store_id,
16 s.name AS store_name,
17 EXTRACT(YEAR FROM o.last_modified_date)::INT AS year,
18 SUM(
19 p.price
20 * o.quantity
21 * (1 - COALESCE(o.discount, 0) / 100.0)
22 ) AS total_revenue
23 FROM store s
24 JOIN sells se
25 ON s.store_id = se.store_id
26 JOIN product p
27 ON se.code = p.code
28 JOIN includes i
29 ON p.code = i.code
30 JOIN "order" o
31 ON i.order_num = o.order_num
32 WHERE o.last_modified_date >=
33 date_trunc('year', CURRENT_DATE) - INTERVAL '2 years'
34 AND o.last_modified_date <
35 date_trunc('year', CURRENT_DATE)
36 GROUP BY
37 s.store_id,
38 s.name,
39 EXTRACT(YEAR FROM o.last_modified_date)
40 ),
41 revenue_comparison AS (
42 SELECT
43 store_id,
44 store_name,
45 MAX(
46 CASE
47 WHEN year = EXTRACT(YEAR FROM CURRENT_DATE)::INT - 2
48 THEN total_revenue
49 ELSE 0
50 END
51 ) AS previous_year_revenue,
52 MAX(
53 CASE
54 WHEN year = EXTRACT(YEAR FROM CURRENT_DATE)::INT - 1
55 THEN total_revenue
56 ELSE 0
57 END
58 ) AS last_year_revenue
59 FROM yearly_revenue
60 GROUP BY
61 store_id,
62 store_name
63 )
64 SELECT
65 store_id,
66 store_name,
67 previous_year_revenue,
68 last_year_revenue,
69 last_year_revenue - previous_year_revenue AS revenue_growth
70 FROM revenue_comparison
71 ORDER BY revenue_growth DESC
72 LIMIT 1;
73END;
74$$;
Note: See TracBrowser for help on using the repository browser.