Home > Back-end >  SQL query for getting count of certain columns for every day across a date range
SQL query for getting count of certain columns for every day across a date range

Time:10-31

I have an 'actions' table in the following format:

id action category_id created_date
1 fff 3 12/11/2020
2 aaa 7 12/04/2021
3 bbb 3 04/01/2016

which is in a one-to-many relationship with 'categories' table (one category can have many actions, category_id is the foreign key above) in the following format:

id name
1 Cat-1
2 Cat-2

I need an API that receives a date range (start and end values) as an input an should return the total number of actions for all categories that take place for every day within that range, like so:

day Cat-1 Cat-2
10/1/2020 22 56
06/8/2011 56 78

Basically showing how many actions of a particular category took place per day in that date range.

My initial way of solving this was to fetch the data grouped by date and then manipulate that in the code. But I want to know if there's a way to do achieve this with SQL itself.

CodePudding user response:

select   created_date                              as day
        ,count(case when name = 'Cat-1'then 1 end) as 'Cat-1'
        ,count(case when name = 'Cat-2'then 1 end) as 'Cat-2'
from     t join t2 using(id)
group by created_date
day Cat-1 Cat-2
2020-12-11 1 0
2021-12-04 0 1

Fiddle

  • Related