Reputation: 157
Let's look at the following table
Name TIMESTAMP STATUS
Task1 01-01-2019 COMPLETE
Task1 01-01-2019 COMPLETE
Task2 01-01-2019 COMPLETE
Task3 02-01-2019 NOT COMPLETE
Task4 01-01-2019 COMPLETE
Task4 02-01-2019 COMPLETE
What I want is the output to be like this:
Date TaskName How many completed?
January Task1 2
January Task2 1
January Task3 0
January Task4 1
February Task1 0
February Task2 0
February Task3 0
February Task4 1
I'm having troubles on figuring out how to group the count each task to a particular date. My table has over 10 tasks and around 100k rows and they need to be grouped by dates so we can see how many tasks were successfully completed for each month.
select DateName(month, DateAdd(month, month([TIMESTAMP]),0)-1) as 'Month',
count(TaskName) as 'Total Processed'
from myTable
where YEAR([TIMESTAMP]) = 2019 and TaskName = 'Task1'
group by month([TIMESTAMP]);
So far I know this will give me the total count of times Task1 was completed for each month in 2019, but I am struggling on how to put each task in this outputted table with their respective names. Can anyone suggest on how I can proceed? Any guidance would be great!
Upvotes: 1
Views: 2184
Reputation: 37368
You can use the following query:
SELECT DATENAME(month,[Timestamp]), Name,
SUM(CASE WHEN [STATUS] = 'Completed' THEN 1 ELSE 0 END) as [Completed]
FROM Table1
GROUP BY DATENAME(month,[Timestamp]), Name
ORDER BY DATENAME(month,[Timestamp]), Name
SUM(CASE WHEN [STATUS] = 'Completed' THEN 1 ELSE 0 END)
will return how much task are completedUpvotes: 1
Reputation: 1271003
Use a cross join
to generate the rows and then left join
to bring in the data:
select m.mm, n.name,
sum(case when t.status = 'COMPLETE' then 1 else 0 end) as num_completed
from (values (convert(date, '2019-01-01'),
convert(date, '2019-02-01')
) m(mm) cross join
(select distinct name
from t
) n left join
t
on t.name = n.name and
t.timestamp >= m.mm and
t.timestamp < dateadd(month, 1, m.mm)
group by m.mm, n.name;
Upvotes: 0
Reputation: 142
Try this.
select
case
when to_char(timestamp, 'MM') = '01' then 'January'
when to_char(timestamp, 'MM') = '02' then 'Febuary'
when to_char(timestamp, 'MM') = '03' then 'March'
when to_char(timestamp, 'MM') = '04' then 'April'
end as month,name, count(status)
from myTable
group by month,name
order by timestamp;
Upvotes: 0