'SQL Substring Case Condition
I'm trying to solve the following question on SQLPAD.
Write a query to return the number of actors whose first name starts with 'A', 'B', 'C', or others. The order of your results doesn't matter. You need to return 2 columns: The first column is the group of actors based on the first letter of their first_name, use the following: 'a_actors', 'b_actors', 'c_actors', 'other_actors' to represent their groups. Second column is the number of actors whose first name matches the pattern.
Table: actor
col_name | col_type
-------------+--------------------------
actor_id | integer
first_name | text
last_name | text
Sample results
actor_category | count
----------------+-------
a_actors | 13
b_actors | 8
So far I've tried this:
select CONCAT(substring(lower(first_name), 2, 1), '_actors') as actor_category , count(*)
FROM actor
group by actor_category
Not sure how to check the others condition.
Solution 1:[1]
One easy option is to use CASE statement and group the result
SELECT actors,COUNT(*) FROM (
SELECT
CASE
WHEN first_name LIKE 'A%' THEN 'a_actors'
WHEN first_name LIKE 'B%' THEN 'b_actors'
WHEN first_name LIKE 'C%' THEN 'c_actors'
ELSE 'other_actors' END AS actors
FROM
actor
)t
GROUP BY t.actors
Solution 2:[2]
You may try this:
select CONCAT(substring(lower(first_name), 2, 1), '_actors') , count(1)
FROM actor
group by CONCAT(substring(lower(first_name), 2, 1), '_actors')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Makubex |
| Solution 2 | Dale K |
