WITH ms AS
(SELECT DISTINCT DATE_TRUNC('month', created_at)::DATE AS mnth
, SUM(costs) OVER (PARTITION BY DATE_TRUNC('month', created_at)::DATE
ORDER BY DATE_TRUNC('month', created_at)::DATE) AS sum_month --numeric
FROM tools_shop.costs
ORDER BY mnth)
SELECT mnth
, sum_month
--, LAG(sum_month, 1, 0) OVER () -- так не работает? ошибка sum_month: function lag(numeric, integer, integer) does not exist
, LAG(CAST(sum_month AS INT), 1, 0) OVER ()
, sum_month - LAG(CAST(sum_month AS INT), 1, 0) OVER () AS month_diff
FROM ms
ORDER BY mnth