WITH
i AS ( SELECT DATE_TRUNC(‘month’, o.order_date::date) AS month, COUNT(DISTINCT
c.company _name) AS number_of_customers FROM northwind.orders AS o JOIN northwind.customers AS c ON o.customer_id = c.customer_id WHERE o.order_date BETWEEN ‘1996-07-01’ AND ‘1998-05-01’ GROUP BY month),
ii AS (SELECT COUNT(DISTINCT customer_id) as total_customers, DATE_TRUNC(‘month’, order_date::date) as month FROM northwind.orders GROUP BY month)
SELECT DATE(i.month) as first_day_of_month, i.number_of_customers, SUM(
ii.total _customers) OVER (ORDER BY i.month ) as total_customers, ROUND(i.number_of_customers::numeric / SUM(
ii.total _customers) OVER (ORDER BY i.month ) * 100, 2) AS conversion_rate FROM i JOIN ii ON i.month=ii.month
В итоговой таблице должны быть следующие поля:
дата первого числа текущего месяца;
количество компаний-заказчиков в текущий месяц;
общее количество компаний-заказчиков за всё предыдущее время, включая текущий месяц;
отношение количества покупателей за текущий месяц к общему количеству покупателей.
Спасибо!
WITH
i AS (
SELECT DATE_TRUNC('month', o.order_date::date) AS month,
COUNT(DISTINCT c.company _name) AS number_of_customers
FROM northwind.orders AS o
JOIN northwind.customers AS c ON o.customer_id = c.customer_id
WHERE o.order_date BETWEEN '1996-07-01' AND '1998-05-01'
GROUP BY month),
ii AS (SELECT COUNT(customer_id) as total_customers,
order_date
FROM northwind.orders
HAVING COUNT(DISTINCT order_id) > 1)
SELECT DATE(i.month) as first_day_of_month,
i.number_of_customers,
SUM( ii.total _customers) as total_customers,
ROUND(number_of_customers::numeric / SUM(total_customers) OVER (ORDER BY month ) * 100, 2) AS conversion_rate
FROM i
JOIN ii ON i.order_date=ii.order_date