Home >Database >Mysql Tutorial >How to Count Job Priorities and Generate Chart-Ready Data?
Conditional counting by column
Problem description:
Suppose you have a table with columns jobId
, jobName
, and Priority
, where Priority
is an integer between 1 and 5. The goal is to generate a query that counts the number of rows with a specific Priority
value and display the results in a format suitable for creating a chart report.
Solution:
To achieve the desired results, you can use a combination of conditional expressions and aggregate functions:
<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>
This query uses a CASE
expression to check for a specific Priority
value and assign a value of 1 if the condition is true and 0 otherwise. These values are then summed for each jobID
and JobName
combination.
GROUP BY
clause ensures that results are grouped by unique values of jobID
and JobName
, thus providing a breakdown of each job count.
By formatting the results in this way, you can easily embed them into chart reports to visualize the distribution of Priority
values for different jobs.
The above is the detailed content of How to Count Job Priorities and Generate Chart-Ready Data?. For more information, please follow other related articles on the PHP Chinese website!