【问题标题】:SQL Substring Case ConditionSQL 子字符串大小写条件
【发布时间】:2021-10-06 11:42:12
【问题描述】:

我正在尝试在 SQLPAD 上解决以下问题。

编写查询以返回名字以“A”、“B”、“C”或其他开头的演员的数量。 结果的顺序无关紧要。 您需要返回 2 列: 第一列是基于名字的第一个字母的演员组,使用以下内容:'a_actors'、'b_actors'、'c_actors'、'other_actors'来表示他们的组。 第二列是名字与模式匹配的演员数量。

表:演员

  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

不知道如何检查其他情况。

【问题讨论】:

  • 将问题的关键部分链接到外部站点是不可接受的。请删除链接,然后完成提问。
  • 并提供minimal reproducible example,即提供示例数据(作为 DDL+DML)您的查询、您想要的结果和您的实际结果。
  • 考虑在名字的第一个字母上使用大小写表达式。不确定为什么要从名字的第二个字符开始子字符串?你会使用 dbfiddle 来测试你的查询吗?

标签: sql sql-server tsql case


【解决方案1】:

你需要这个。这个问题实际上是针对 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')

【讨论】:

  • 它实际上并不能帮助人们为他们做功课。
  • 同意先生。但这与家庭作业无关。它是关于解决问题的。
  • 同样的,这是一个面试问题,只是给出答案意味着OP什么都学不到。
  • 你也在鼓励不好的问题。正如上面的 Tim cmets,问题需要是独立的,而不是依赖于外部链接。
【解决方案2】:

一个简单的选择是使用 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

【讨论】:

    【解决方案3】:

    你可以试试这个:

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

    【讨论】:

    • 与我对另一个答案所做的相同的 cmets。
    猜你喜欢
    • 2016-01-25
    • 2023-03-22
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    • 2021-10-14
    相关资源
    最近更新 更多