简体   繁体   中英

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.

you need this. The question actually says specific for a,b,c and others. You are not doing specific for abc

with getFistChar AS
(
    select substring(LOWER(first_name), 1, 1) ac
    from actor
)
select CONCAT(ac, '_actors')actor_category, COUNT(1)count
from getFistChar
where ac in ('a', 'b', 'c')
Group By actor_category
UNION
select 'other_actors'actor_category, sum(1)
from getFistChar
where ac not in ('a', 'b', 'c')

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

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM