From d77e3e098a56b90962ec936923baa959ac7fa6bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=96=D1=83=D0=BB=D1=8C=20=D0=9A=D0=B8=D1=80=D0=B8=D0=BB?= =?UTF-8?q?=D0=BB?= <118897479+KirillZhul@users.noreply.github.com> Date: Mon, 29 May 2023 13:19:11 +0300 Subject: [PATCH] Update tmp_rfm_frequency.sql --- tmp_rfm_frequency.sql | 46 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/tmp_rfm_frequency.sql b/tmp_rfm_frequency.sql index 8b13789..65b0a62 100644 --- a/tmp_rfm_frequency.sql +++ b/tmp_rfm_frequency.sql @@ -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;