SQL 子字符串大小写条件

SQL Substring Case Condition

我正在尝试在 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: 演员

  col_name   | col_type
-------------+--------------------------
 actor_id    | integer
 first_name  | text
 last_name   | text

示例结果

actor_category | count
----------------+-------
 a_actors       |    13
 b_actors       |     8

到目前为止我试过这个:

select  CONCAT(substring(lower(first_name), 2, 1), '_actors') as actor_category , count(*)
FROM actor
group by actor_category

不确定如何检查其他条件。

你需要这个。这个问题实际上是针对 a、b、c 和其他人说的。您没有针对 a.b.c

执行特定操作
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')

你可以试试这个:

select  CONCAT(substring(lower(first_name), 2, 1), '_actors')  , count(1)
FROM actor
group by CONCAT(substring(lower(first_name), 2, 1), '_actors')

一个简单的选择是使用 CASE 语句并对结果进行分组

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