-
Notifications
You must be signed in to change notification settings - Fork 0
/
task_3.sql
43 lines (43 loc) · 1.06 KB
/
task_3.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
SELECT *
FROM crosstab(
$$
SELECT
to_char(to_timestamp (month::text, 'MM'), 'Month') as month_name,
selling_rank,
name
FROM (
SELECT
month,
total_qty,
name,
price,
price * total_qty as total_income,
RANK() over (
PARTITION BY month
ORDER BY price * total_qty DESC
) as selling_rank
FROM (
SELECT
EXTRACT('month' from date::timestamp) as month,
"PURCHASE".product_key,
SUM(qty) as total_qty
FROM "PURCHASE"
LEFT JOIN "PRODUCT" on "PURCHASE".product_key = "PRODUCT".product_key
LEFT JOIN "PRODUCT_CATEGORY" on "PRODUCT_CATEGORY".category_key = "PRODUCT".category_key
WHERE
date >= '2018-01-01' AND
date <= '2018-12-31' AND
category = 'Игрушки'
GROUP BY EXTRACT('month' from date::timestamp), "PURCHASE".product_key
) as total_sells
JOIN "PRODUCT" ON total_sells.product_key = "PRODUCT".product_key) as total
WHERE selling_rank < 4
ORDER BY month ASC, selling_rank ASC
$$,
'SELECT * FROM generate_series(1, 3)'
) as (
Month text,
First_sell text,
Second_sell text,
Third_sell text
)