generated from yandex-praktikum/de-project-sprint-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
bd28f51
commit d77e3e0
Showing
1 changed file
with
46 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,47 @@ | ||
CREATE TABLE analysis.tmp_rfm_frequency ( | ||
user_id INT NOT NULL PRIMARY KEY, | ||
frequency INT NOT NULL CHECK(frequency >= 1 AND frequency <= 5) | ||
); | ||
|
||
SELECT o.user_id, | ||
COUNT( | ||
CASE | ||
WHEN os.key = 'Closed' then 1 | ||
END | ||
) AS orders_closed | ||
FROM | ||
analysis.orders o LEFT JOIN analysis.orderstatuses os | ||
ON o.status = os.id | ||
GROUP BY o.user_id | ||
ORDER BY orders_closed DESC; | ||
|
||
WITH num_orders AS | ||
(SELECT o.user_id, | ||
COUNT (CASE | ||
WHEN os.key = 'Closed' THEN 1 | ||
END) AS orders_closed | ||
FROM analysis.orders o | ||
LEFT JOIN analysis.orderstatuses os ON o.status = os.id | ||
GROUP BY o.user_id | ||
ORDER BY orders_closed DESC) | ||
SELECT u.id, | ||
NTILE(5) OVER( | ||
ORDER BY nrds.orders_closed) AS frequency | ||
FROM analysis.users u | ||
INNER JOIN num_orders nrds ON u.id = nrds.user_id; | ||
|
||
INSERT INTO analysis.tmp_rfm_frequency (user_id, frequency) | ||
WITH num_orders AS | ||
(SELECT o.user_id, | ||
COUNT (CASE | ||
WHEN os.key = 'Closed' THEN 1 | ||
END) AS orders_closed | ||
FROM analysis.orders o | ||
LEFT JOIN analysis.orderstatuses os ON o.status = os.id | ||
GROUP BY o.user_id | ||
ORDER BY orders_closed DESC) | ||
SELECT u.id, | ||
NTILE(5) OVER( | ||
ORDER BY nrds.orders_closed) AS frequency | ||
FROM analysis.users u | ||
INNER JOIN num_orders nrds ON u.id = nrds.user_id; |