Home >Database >Mysql Tutorial >How to Count Conditional Column Values in SQL: A Priority-Based Example?
Consider a table called "Jobs" with the following structure:
<code>jobId, jobName, Priority</code>
Where "Priority" is an integer between 1 and 5.
Problem statement:
You need to create a query that counts the number of rows for each priority level (1 to 5) in the "Jobs" table. The query should return columns named "Priority1" through "Priority5", respectively, representing these counts.
Solution:
To do this, use the following SQL statement:
<code class="language-sql">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;</code>
Explanation:
NOTE: If you wish to exclude "jobId" and "jobName", just remove them from the SELECT and GROUP BY clauses.
The above is the detailed content of How to Count Conditional Column Values in SQL: A Priority-Based Example?. For more information, please follow other related articles on the PHP Chinese website!