COUNT_IF
The suffix _IF
can be appended to the name of any aggregate function. In this case, the aggregate function accepts an extra argument – a condition.
Analyze Syntax
func.count_if(<column>, <cond>)
Analyze Examples
func.count_if(table.status, table.status=='Completed').alias('completed_orders')
| completed_orders |
|------------------|
| 3 |
SQL Example
COUNT_IF(<column>, <cond>)
SQL Examples
Create a Table and Insert Sample Data
CREATE TABLE orders (
id INT,
customer_id INT,
status VARCHAR,
total FLOAT
);
INSERT INTO orders (id, customer_id, status, total)
VALUES (1, 1, 'completed', 100),
(2, 2, 'completed', 200),
(3, 1, 'pending', 150),
(4, 3, 'completed', 250),
(5, 2, 'pending', 300);
Query Demo: Count Completed Orders
SELECT COUNT_IF(status, status = 'completed') AS completed_orders
FROM orders;
Result
| completed_orders |
|------------------|
| 3 |
Last modified June 11, 2024 at 8:46 PM EST: adding aggregate functions (68e518e)