finki-main
main
|
Last change
on this file since 33517cc was 62b2964, checked in by Klimentina Efremova <klimentina08642@…>, 2 weeks ago |
|
Project Handcraft Marketplace
|
-
Property mode
set to
100644
|
|
File size:
1.7 KB
|
| Line | |
|---|
| 1 | CREATE OR REPLACE FUNCTION get_stores_by_monthly_profit_and_revenue_growth()
|
|---|
| 2 | RETURNS TABLE (
|
|---|
| 3 | store_id INT,
|
|---|
| 4 | store_name TEXT,
|
|---|
| 5 | month_and_year TEXT,
|
|---|
| 6 | monthly_profit NUMERIC,
|
|---|
| 7 | previous_month_revenue NUMERIC,
|
|---|
| 8 | current_month_revenue NUMERIC,
|
|---|
| 9 | revenue_growth NUMERIC
|
|---|
| 10 | )
|
|---|
| 11 | LANGUAGE plpgsql
|
|---|
| 12 | AS $$
|
|---|
| 13 | BEGIN
|
|---|
| 14 | RETURN QUERY
|
|---|
| 15 | WITH monthly_revenue AS (
|
|---|
| 16 | SELECT
|
|---|
| 17 | s.store_id,
|
|---|
| 18 | s.name AS store_name,
|
|---|
| 19 | DATE_TRUNC('month', o.last_modified_date) AS month_date,
|
|---|
| 20 | SUM(
|
|---|
| 21 | p.price
|
|---|
| 22 | * o.quantity
|
|---|
| 23 | * (1 - COALESCE(o.discount, 0) / 100.0)
|
|---|
| 24 | ) AS revenue
|
|---|
| 25 | FROM store s
|
|---|
| 26 | JOIN sells se
|
|---|
| 27 | ON s.store_id = se.store_id
|
|---|
| 28 | JOIN product p
|
|---|
| 29 | ON se.code = p.code
|
|---|
| 30 | JOIN includes i
|
|---|
| 31 | ON p.code = i.code
|
|---|
| 32 | JOIN "order" o
|
|---|
| 33 | ON i.order_num = o.order_num
|
|---|
| 34 | GROUP BY
|
|---|
| 35 | s.store_id,
|
|---|
| 36 | s.name,
|
|---|
| 37 | DATE_TRUNC('month', o.last_modified_date)
|
|---|
| 38 | ),
|
|---|
| 39 | revenue_with_previous AS (
|
|---|
| 40 | SELECT
|
|---|
| 41 | store_id,
|
|---|
| 42 | store_name,
|
|---|
| 43 | month_date,
|
|---|
| 44 | revenue,
|
|---|
| 45 | LAG(revenue) OVER (
|
|---|
| 46 | PARTITION BY store_id
|
|---|
| 47 | ORDER BY month_date
|
|---|
| 48 | ) AS previous_month_revenue
|
|---|
| 49 | FROM monthly_revenue
|
|---|
| 50 | )
|
|---|
| 51 | SELECT
|
|---|
| 52 | store_id,
|
|---|
| 53 | store_name,
|
|---|
| 54 | TO_CHAR(month_date, 'YYYY-MM') AS month_and_year,
|
|---|
| 55 | revenue AS monthly_profit,
|
|---|
| 56 | COALESCE(previous_month_revenue, 0) AS previous_month_revenue,
|
|---|
| 57 | revenue AS current_month_revenue,
|
|---|
| 58 | revenue - COALESCE(previous_month_revenue, 0) AS revenue_growth
|
|---|
| 59 | FROM revenue_with_previous
|
|---|
| 60 | ORDER BY
|
|---|
| 61 | monthly_profit DESC,
|
|---|
| 62 | revenue_growth DESC;
|
|---|
| 63 | END;
|
|---|
| 64 | $$; |
|---|
Note:
See
TracBrowser
for help on using the repository browser.