This is more of a conceptual question. I'm trying to compare the sales that have happened this year with the last year. But the comparison should be dynamic, as in, for this year I consider the sales that have happened till yesterday, and I need to consider the sales for the previous year till the same date last year as well.
For example, today is Dec 24th, so for 2021 I aggregate the sales till Dec 23rd, and I need to do the same for 2020 as well i.e. till Dec 23rd of 2020. And for tomorrow's report the aggregate should be till Dec 24th of 2021 and Dec 24th of 2020 respectively.
My code so far:
SELECT product_category,
SUM(CASE WHEN purchase_date >= '2021-01-01' AND purchase_date < CURRENT_DATE THEN sales_revenue ELSE 0 END) AS revenue_2021,
SUM(CASE WHEN purchase_date >= '2020-01-01' AND purchase_date < '2021-01-01' THEN sales_revenue ELSE 0 END) AS revenue_2020
FROM sales_table
GROUP BY 1
ORDER BY 1
Here, for 2021, my code works. But for 2020 it would give the whole year (2020's) sum. Is there anyway I can make this dynamic for 2020 just the same way it happens for 2021?
CodePudding user response:
SELECT product_category,
SUM(CASE WHEN purchase_date >= DATEADD(yy, DATEDIFF(yy, 0, CURRENT_DATE), 0)
AND purchase_date < CURRENT_DATE THEN sales_revenue ELSE 0 END) AS revenue_2021,
SUM(CASE WHEN purchase_date >= DATEADD(yy, DATEDIFF(yy, 0, CURRENT_DATE)-1, 0) AND purchase_date < dateadd(yy, -1, CURRENT_DATE) THEN sales_revenue ELSE 0 END) AS revenue_2020
FROM sales_table
WHERE
purchase_date >= DATEADD(yy, DATEDIFF(yy, 0, CURRENT_DATE)-1, 0)
GROUP BY 1
ORDER BY 1
CodePudding user response:
I figured this out by myself and this seems to work.
SELECT EXTRACT(YEAR FROM DATE_TRUNC('YEAR',purchase_date) AS Year,
product_category,
SUM(sales_revenue)
FROM sales_table
WHERE DATE_PART('MONTH',purchase_date)*100 DATE_PART('DAY',purchase_date_time)
< DATE_PART('MONTH',CURRENT_DATE)*100 DATE_PART('DAY',CURRENT_DATE)
GROUP BY 1,2
ORDER BY 1,2