【问题标题】:How to check if a string contains a word at a case statement - SQLite如何在 case 语句中检查字符串是否包含单词 - SQLite
【发布时间】:2020-01-15 21:46:03
【问题描述】:

这是我的代码:

SELECT 
CASE your_text
  WHEN contains('hate') THEN 'hater'
  WHEN contains('love') THEN 'lover'
  ELSE 'other'
END haterOrLover,
count(*) AS total_count
FROM a_table
GROUP BY haterOrLover

如果只存在 contains()!

我想统计一下有多少仇敌、恋人以及这种格式的结果:

+--------------+-------------+  
| haterOrLover | total_count |  
+--------------+-------------+  
| hater        | 1           |  
+--------------+-------------+  
| lover        | 2           |  
+--------------+-------------+  
| other        | 1           |  
+--------------+-------------+

试过了:

WHEN your_text like '%hate%' THEN 'hater'
WHEN '%hate%' THEN 'hater'

但没用。

如何检查记录是否包含“your_text”列中的特定单词?

编辑
如何重现:

CREATE TABLE a_table
(
id         char(10)      PRIMARY KEY,
your_text  char(250)     NOT NULL
);

INSERT INTO a_table
    (id, your_text)
VALUES
    (1, 'I love dogs'),
    (2, 'I hate cats'),
    (3, 'I like rabits'),
    (4, 'I love haskis');

谢谢


解决方案

SELECT 
CASE
  WHEN your_text like '%hate%' THEN 'hater'
  WHEN your_text like '%love%' THEN 'lover'
  ELSE 'other'
END haterOrLover,
count(*) AS total_count
FROM a_table
GROUP BY haterOrLover

【问题讨论】:

标签: sql string sqlite substring case


【解决方案1】:

试试看:

with cte as (
SELECT 
CASE when your_text like ('%hate%') THEN 'hater'
     when your_text like ('%love%') THEN 'lover'
     ELSE 'other'
     END haterOrLover FROM a_table )
select haterOrLover , count(*) as total_count from cte
group by (haterOrLover)

【讨论】:

  • 感谢工作!实际上,CASE 之后的“your_text”在初始代码中是错误的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-25
  • 1970-01-01
  • 1970-01-01
  • 2011-05-09
  • 2011-05-20
相关资源
最近更新 更多