CPM по источникам рекламы за последний месяц
SQL, по которому посчитано
WITH last_month AS (
SELECT date_trunc('month', max(date)) AS month_start
FROM ads
),
agg AS (
SELECT source,
sum(impressions) AS impressions,
sum(cost) AS cost
FROM ads, last_month
WHERE date >= last_month.month_start
AND date < last_month.month_start + INTERVAL 1 MONTH
GROUP BY source
)
SELECT source,
impressions,
round(cost, 0) AS cost,
round(cost / nullif(impressions, 0) * 1000, 2) AS cpm
FROM agg
ORDER BY cpm DESC