Я занимаюсь анализом Recency-Frequency-Monetary и, хотя у меня есть модель, работающая на Python, я пытаюсь реализовать ее на SQL, потому что производственный код состоит в основном из PHP (Oracle 12c fwiw или также может быть выполнен в postgres),В Интернете я видел пример, в котором добавлялись новые столбцы с использованием ntile, однако я хочу использовать эквивалент квантиля (например, разделение ребер корзины недавности до 0,0,74,321 для 5 квантилей).Я начал идти по маршруту ниже, но есть ли более аккуратный путь?
SELECT
percentile_disc(0.2) within group (order by recency) as recency_1_quin,
percentile_disc(0.4) within group (order by recency) as recency_2_quin,
percentile_disc(0.6) within group (order by recency) as recency_3_quin,
percentile_disc(0.8) within group (order by recency) as recency_4_quin,
percentile_disc(0.2) within group (order by monetary_value) as monetary_1_quin,
percentile_disc(0.4) within group (order by monetary_value) as monetary_2_quin,
percentile_disc(0.6) within group (order by monetary_value) as monetary_3_quin,
percentile_disc(0.8) within group (order by monetary_value) as monetary_4_quin,
percentile_disc(0.2) within group (order by frequency) as frequency_1_quin,
percentile_disc(0.4) within group (order by frequency) as frequency_2_quin,
percentile_disc(0.6) within group (order by frequency) as monetary_3_quin,
percentile_disc(0.8) within group (order by frequency) as monetary_4_quin
FROM RFM;
Редактировать: С помощью, это то, где я нахожусь, но застрял в группе внутри CTE.[42000] [978] ORA-00978: функция вложенной группы без GROUP BY
RFM AS (
SELECT SRC_USER_ID,
COUNT(distinct PICKUP_DATE) -1 as frequency,
(MAX(PICKUP_DATE) - MIN(PICKUP_DATE)) as recency,
(TO_DATE ('2018/05/12', 'yyyy/mm/dd') - MIN(PICKUP_DATE)) as T,
SUM(PRICE_TOTAL) AS monetary_value
FROM TRANSACTIONS
group by SRC_USER_ID
ORDER BY frequency DESC),
MAX_VALUES AS (
select sum(max(recency) + 0.0000000001) as max_recency,
sum(max(frequency) + 0.00000001) as max_frequency,
sum(max(monetary_value) + 0.000000001) as max_monetary
FROM RFM
)
SELECT
SRC_USER_ID,
recency,
frequency,
monetary_value,
WIDTH_BUCKET(recency, 0, max_recency, 5) "recency_quantile",
WIDTH_BUCKET(frequency, 0, max_frequency, 5) "frequency_quantile",
WIDTH_BUCKET(monetary_value, 0, max_monetary, 5) "monetary_quantile"
FROM RFM, MAX_VALUES