【问题标题】:MySQL query to get count of repeating characters from a stringMySQL查询以获取字符串中重复字符的计数
【发布时间】:2020-02-19 13:45:02
【问题描述】:

我的目标数据/表格:

mysql> select firstname from empl;
+-----------+
| firstname |
+-----------+
| Abhishek  |
| Arnab     |
| Aamaaan   |
| Arbaaz    |
| Mohon     |
| Parikshit |
| Tom       |
| Koustuv   |
| Amit      |
| Bibhishana|
| abCCdEeff |
+-----------+
11 rows in set (0.00 sec)

期望的输出:

为在名字中重复的每个区分大小写字母返回一行三列:column_one 是 x—其中重复的名字找到信件; column_two 是 y——重复的最左边唯一字母; column_three 是 z -字母在单词中出现的次数

---------------+-------+-----+
 firstname,x   | str,y |cnt,z|
---------------+-------+-----+
 Aamaaan       | a     | 4   | 
 Arbaaz        | a     | 2   | 
 Mohon         | o     | 2   | 
 Parikshit     | i     | 2   | 
 Koustuv       | u     | 2   |  
 Bhibhishana   | h     | 3   | 
 Bhibhishana   | i     | 2   | 
 Bhibhishana   | a     | 2   | 
 abcCCdEeff    | C     | 2   |
 abcCCdEeff    | f     | 2   |

迄今为止我最好的尝试:

WITH CTE AS
(
    SELECT firstname, CONVERT(LEFT(firstname,1),CHAR) AS Letter, RIGHT(firstname, LENGTH(firstname)-1) AS Remainder
    FROM empl
    WHERE LENGTH(firstname)>1
    UNION ALL
    SELECT firstname, CONVERT(LEFT(Remainder,1),CHAR) AS Letter,
        RIGHT(Remainder, LENGTH(Remainder)-1) AS Remainder
    FROM CTE
    WHERE LENGTH(Remainder)>0
)
SELECT firstname, Letter, ASCII(Letter) AS CharCode, COUNT(Letter) AS CountOfLetter
FROM CTE
GROUP BY firstname, Letter, ASCII(Letter)
HAVING COUNT(Letter)>2

【问题讨论】:

  • 使用字母 a - z 加入帮助表 / cte。检查长度(替换 col, char, '')
  • 嗨@jarlh,我尝试使用CTE,但没有运气,你能帮我把你的评论变成答案吗
  • 好棘手的问题,通过查询很难做到,除非有人非常擅长编写查询。

标签: mysql sql subquery mysql-8.0 regex-recursion


【解决方案1】:

使用递归CTEs 获取所有字母A-Za-z 并加入表格:

with 
  recursive u_letters as (
    select 'A' letter
    union all
    select char(ascii(letter) + 1) from u_letters
    where letter < 'Z'
  ),
  l_letters as (
    select 'a' letter
    union all
    select char(ascii(letter) + 1) from l_letters
    where letter < 'z'
  ),
  letters as (
    select * from u_letters
    union all
    select * from l_letters
  ),
  results as (
    select e.firstname, l.letter,
      length(e.firstname) - length(replace(e.firstname, l.letter, '')) cnt
    from empl e inner join letters l
    on binary e.firstname like concat('%', l.letter, '%')
  )
select * from results                                   
where cnt > 1 

请参阅demo
结果:

| firstname   | letter | cnt |
| ----------- | ------ | --- |
| Abhishek    | h      | 2   |
| Aamaaan     | a      | 4   |
| Arbaaz      | a      | 2   |
| Mohon       | o      | 2   |
| Parikshit   | i      | 2   |
| Koustuv     | u      | 2   |
| Bibhishana  | a      | 2   |
| Bibhishana  | h      | 2   |
| Bibhishana  | i      | 2   |
| abCCdEeff   | C      | 2   |
| abCCdEeff   | f      | 2   |

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-25
    • 2013-01-05
    • 2013-05-16
    • 2012-07-23
    • 2013-03-29
    • 1970-01-01
    相关资源
    最近更新 更多