0

我的目标数据/表格:

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—<strong>找到重复字母的名字;column_two 是 y——<strong>重复的最左边唯一字母;column_three 是 z—<strong>字母在 word 中出现的次数

---------------+-------+-----+
 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
4

1 回答 1

2

使用 recursiveCTE获取所有字母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 

请参阅演示
结果:

| 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   |
于 2020-02-21T12:22:02.757 回答