The table I am working with is called 'transactions'. The columns are id (customer id), amount (amount spent by customer), timestamp (time of purchase).
I am trying to query:
- yesterdays revenue: sum of amount.
- percent difference from 8 day's ago revenue to yesterday's revenue.
- MTD.
- percent difference from last months MTD to this months MTD.
SAMPLE DATA
| id | amount | timestamp |
|---|---|---|
| 1 | 50 | 2021-12-01 |
| 2 | 60 | 2021-12-02 |
| 3 | 70 | 2021-11-05 |
| 4 | 80 | 2022-01-26 |
| 5 | 90 | 2022-01-25 |
| 6 | 20 | 2022-01-26 |
| 7 | 80 | 2022-01-19 |
EXPECTED OUTPUT
| yesterday_revenue | pct_change_week_ago | mtd | pct_change_month_prior |
|---|---|---|---|
| 100 | 0.25 | 270 | 0.50 |
This is my code. The percent change columns are both incorrect. Please help.
select
-- yesterday
sum(case when timestamp::date = current_date - 1 then amount else null end) yesterday_revenue,
-- yesterday v. last week
(sum(case when timestamp::date > current_date - 1 then amount else null end) - sum(case when timestamp::date = current_date - 8 then amount else null end))
/ sum(case when timestamp::date = current_date - 8 then amount else null end) pct_change_week_ago,
-- mtd
sum(case when date_trunc('month',timestamp) = date_trunc('month',CURRENT_DATE -1) then amount else null end) mtd,
-- mtd v. month prior
(sum(case when date_trunc('month',timestamp) = date_trunc('month',CURRENT_DATE -1) then amount else null end) - sum(case when date_trunc('month',timestamp) = date_trunc('month',CURRENT_DATE -1) - interval '1 month'
and date_part('day',timestamp ) <= date_part('day', CURRENT_DATE -1) then amount else null end))
/ sum(case when date_trunc('month',timestamp) = date_trunc('month',CURRENT_DATE -1) - interval '1 month'
and date_part('day',timestamp ) <= date_part('day', CURRENT_DATE -1) then amount else null end) pct_change_month_prior
from transactions