Skip to content

Commit

Permalink
Update tmp_rfm_frequency.sql
Browse files Browse the repository at this point in the history
  • Loading branch information
KirillZhul authored May 29, 2023
1 parent bd28f51 commit d77e3e0
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions tmp_rfm_frequency.sql
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;

0 comments on commit d77e3e0

Please sign in to comment.