Home > Database > Mysql Tutorial > How to Achieve 'SUM IF' and 'COUNT IF' Functionality in MySQL with Conditional Aggregation?

How to Achieve 'SUM IF' and 'COUNT IF' Functionality in MySQL with Conditional Aggregation?

Mary-Kate Olsen
Release: 2024-11-13 14:32:02
Original
375 people have browsed it

How to Achieve 'SUM IF' and 'COUNT IF' Functionality in MySQL with Conditional Aggregation?

MySQL Conditional Aggregation: Unlocking 'SUM IF' and 'COUNT IF' Capabilities

In MySQL, performing conditional aggregation, such as summing or counting values based on specific conditions, can be achieved through the use of CASE statements. This allows you to flexibly apply criteria to your aggregation operations.

Consider the following scenario: you have a table with columns 'hour' and 'kind' (which can hold values 1, 2, or 3). You want to count the number of rows, calculate the total hours, and determine the count of rows where 'kind' is equal to 1.

Initially, you might try the following queries:

SELECT count(id), SUM(hour) as totHour, SUM( IF ( kind = 1, 1, 0 ) ) as countKindOne
Copy after login

or

SELECT count(id), SUM(hour) as totHour, COUNT( IF ( kind = 1 ) ) as countKindOne
Copy after login

However, these queries will likely result in an error. To resolve this, you need to utilize a CASE statement within the aggregation operations:

SELECT count(id), 
    SUM(hour) as totHour, 
    SUM(case when kind = 1 then 1 else 0 end) as countKindOne
Copy after login

In this CASE statement, we specify that if the value in the 'kind' column is 1, we return 1, otherwise we return 0. This allows us to conditionally count the rows where 'kind' is equal to 1.

The above is the detailed content of How to Achieve 'SUM IF' and 'COUNT IF' Functionality in MySQL with Conditional Aggregation?. 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