Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Count on a field

If I had a table like this:

jobId, jobName, Priority 

Whereby Priority can be an integer between 1 to 5.

Since I would need this query for generating a chart on report, I would need to display the jobid, jobname and 5 fields called Priority1, Priority2, Priority3, Priority4. Priority5.

Priority1 should count the amount of rows where priority field has the value of 1.

Priority2 should count the amount of rows where priority field has the value of 2.

Priority3 should count the amount of rows where priority field has the value of 3.

etc

How would I do that in a quick and performant manner?

like image 201
Houman Avatar asked Aug 17 '09 13:08

Houman


People also ask

How do you apply condition on count?

COUNT() with HAVINGThe HAVING clause with SQL COUNT() function can be used to set a condition with the select statement. The HAVING clause is used instead of WHERE clause with SQL COUNT() function.

Can you put a select statement in a count?

SQL SELECT statement can be used along with COUNT(*) function to count and display the data values.

Are count (*) and count () the same function?

Since it doesn't matter which value you put in the parentheses, it follows that COUNT(*) and COUNT(1) are precisely the same. They are precisely the same because the value in the COUNT() parentheses serves only to tell the query what it will count.


2 Answers

I think you may be after

select      jobID, JobName,     sum(case when Priority = 1 then 1 else 0 end) as priority1,     sum(case when Priority = 2 then 1 else 0 end) as priority2,     sum(case when Priority = 3 then 1 else 0 end) as priority3,     sum(case when Priority = 4 then 1 else 0 end) as priority4,     sum(case when Priority = 5 then 1 else 0 end) as priority5 from     Jobs group by      jobID, JobName 

However I am uncertain if you need to the jobID and JobName in your results if so remove them and remove the group by,

like image 50
David Raznick Avatar answered Nov 13 '22 08:11

David Raznick


Using COUNT instead of SUM removes the requirement for an ELSE statement:

SELECT jobId, jobName,     COUNT(CASE WHEN Priority=1 THEN 1 END) AS Priority1,     COUNT(CASE WHEN Priority=2 THEN 1 END) AS Priority2,     COUNT(CASE WHEN Priority=3 THEN 1 END) AS Priority3,     COUNT(CASE WHEN Priority=4 THEN 1 END) AS Priority4,     COUNT(CASE WHEN Priority=5 THEN 1 END) AS Priority5 FROM TableName GROUP BY jobId, jobName 
like image 42
taur Avatar answered Nov 13 '22 06:11

taur