Home > Database > Mysql Tutorial > How to Efficiently Count Conditional Rows by Priority in SQL?

How to Efficiently Count Conditional Rows by Priority in SQL?

Mary-Kate Olsen
Release: 2025-01-10 07:39:45
Original
575 people have browsed it

How to Efficiently Count Conditional Rows by Priority in SQL?

SQL efficiently counts conditional rows sorted by priority

Suppose you have a table that stores job information, with a column indicating priority (an integer between 1 and 5). To generate a chart report that displays job counts by priority, you need to create five additional fields, each of which counts the number of rows with a specific priority value.

The solution lies in using the CASE statement in the SELECT query. The following code provides an efficient and performant way to achieve your desired output:

<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>
Copy after login

This query essentially uses the SUM() function to count the number of rows for each priority level. However, it also uses the CASE statement to exclude rows that do not meet certain priority conditions. The result is a table with additional fields representing condition counts.

To include only the job count and not the jobID and JobName in the results, simply remove these columns from the SELECT statement and remove the GROUP BY clause.

The above is the detailed content of How to Efficiently Count Conditional Rows by Priority in SQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template