Count number of unique characters in a string

后端 未结 6 1193
挽巷
挽巷 2020-12-11 03:41

I\'m looking for a sql statement to count the number of unique characters in a string.

e.g.

3333333333 -> returns 1
1113333333 -> returns 2
111         


        
6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-11 04:11

    There is no direct or easy way of doing it. You may need to write a store function to do the job and by looking at all the characters you may expect in the data. Here is an example for just digits , which could be extended for all the characters in a stored function

    mysql> select * from test ;
    +------------+
    | val        |
    +------------+
    | 11111111   |
    | 111222222  |
    | 1113333222 |
    +------------+
    
    
    select 
    val, 
    sum(case when locate('1',val) > 0 then 1 else 0 end ) 
    + sum( case when locate('2',val) > 0 then 1 else 0 end)
    + sum(case when locate('3',val) > 0 then 1 else 0 end)
    +sum(case when locate('4',val) > 0 then 1 else 0 end ) as occurence
    from test group by val
    
    
    +------------+-----------+
    | val        | occurence |
    +------------+-----------+
    | 11111111   |         1 |
    | 111222222  |         2 |
    | 1113333222 |         3 |
    +------------+-----------+
    

    Or if you have enough time , create a lookup table with all the characters you could think of. And make the query in 2 lines

    mysql> select * from test ;
    +------------+
    | val        |
    +------------+
    | 11111111   |
    | 111222222  |
    | 1113333222 |
    +------------+
    3 rows in set (0.00 sec)
    
    mysql> select * from look_up ;
    +------+------+
    | id   | val  |
    +------+------+
    |    1 | 1    |
    |    2 | 2    |
    |    3 | 3    |
    |    4 | 4    |
    +------+------+
    4 rows in set (0.00 sec)
    
    select 
    t1.val, 
    sum(case when locate(t2.val,t1.val) > 0 then 1 else 0 end ) as occ 
    from test t1,(select * from look_up)t2 
    group by t1.val ;
    
    +------------+------+
    | val        | occ  |
    +------------+------+
    | 11111111   |    1 |
    | 111222222  |    2 |
    | 1113333222 |    3 |
    +------------+------+
    

提交回复
热议问题