Home > OS >  Get last 7 days, 20 days and YTD count
Get last 7 days, 20 days and YTD count

Time:06-07

I have a table with columns sales_date, sales_id, sales_region and I am looking to display the count of sales for the past 7 days, 20 days and YTD.

I have this query below that returns the correct count for 7 and 20 days but the YTD shows the count minus the 7 and 20 days. How can I tweak this query to show the YTD correctly? Thank you

select region,
case when current_date- sales_date <=7 then 'Past7'
    when current_date- sales_date <=28 then 'Past20'
    else 'YTD' 

end as "trendsales",
   count(*) as salescount
from sales_table
where sales_date >= '2022-01-01'
group by 1

CodePudding user response:

you could pivot it a bit. 4 columns Region, YTD, Past7, and Past20 would be columns.

select region,
sum(case when current_date- sales_date <=7 then 1 else 0 end) as Past7,
sum(case when current_date- sales_date <=28 then 1 else 0 end) as Past20,
count(*) as YTD
from sales_table
where sales_date >= '2022-01-01'
group by 1
  • Related