Introduction
Use CASE with aggregate functions to count or sum values conditionally in a group of data.
SELECT column1, AGGREGATE_FUNCTION(CASE WHEN condition THEN value ELSE alternative END) AS alias FROM table_name GROUP BY column1;
SELECT department, SUM(CASE WHEN gender = 'F' THEN 1 ELSE 0 END) AS female_count FROM employees GROUP BY department;
SELECT product_category, AVG(CASE WHEN rating >= 4 THEN rating ELSE NULL END) AS avg_high_rating FROM reviews GROUP BY product_category;
SELECT city, COUNT(CASE WHEN order_total > 100 THEN 1 ELSE NULL END) AS big_orders FROM orders GROUP BY city;
CREATE TABLE sales ( region VARCHAR(20), amount INT ); INSERT INTO sales VALUES ('North', 120), ('North', 80), ('South', 150), ('South', 50), ('East', 200), ('East', 90); SELECT region, SUM(CASE WHEN amount > 100 THEN amount ELSE 0 END) AS high_sales_total, COUNT(CASE WHEN amount > 100 THEN 1 ELSE NULL END) AS high_sales_count FROM sales GROUP BY region;
SELECT SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) FROM users;score is greater than 50 using CASE inside COUNT?sales with columns region and amount, what is the output of this query?SELECT region, SUM(CASE WHEN amount > 100 THEN amount ELSE 0 END) AS big_sales FROM sales GROUP BY region;
SELECT department, COUNT(CASE department = 'HR' THEN 1 ELSE NULL END) FROM employees GROUP BY department;
Pass the test and this pattern moves unknown