1

select userid from user;

+---------+
| userid  |
+---------+
| .1.     |
| .1.1.   |
| .1.2.   |
| .1.2.1. |
+---------+

I want the result like this :

+---------+-------+
| userid  | count |
+---------+-------+
| .1.     | 2     |
| .1.1.   | 3     |
| .1.2.   | 3     |
| .1.2.1. | 4     |
+---------+-------+

The count field is about how many the dots are in a row.

What is the sql for that? Thank you

Cazhu Yuu
  • 11
  • 1
  • 3
    Does this answer your question? [Count the number of occurrences of a string in a VARCHAR field?](https://stackoverflow.com/questions/12344795/count-the-number-of-occurrences-of-a-string-in-a-varchar-field) – Markus Zeller Dec 06 '19 at 08:39

4 Answers4

2

Do the length of userid, minus the length of replacing userid's dots with nothing

SELECT
  userid, 
  LENGTH(userid) - LENGTH(REPLACE(userid, '.', '')) as count 
FROM user

IN GENERAL for this technique we should carefully consider whether to use LENGTH or CHAR_LENGTH, the first one counts the number of bytes that make up the string, the second the number of chars. In this case it won't matter but it could in future if you use this technique on Unicode strings where the characters are represented by more than one byte

Caius Jard
  • 72,509
  • 5
  • 49
  • 80
2

You coudl check for the length before and after repalce the dot

  select  userid, length(userid) - length(replace(userid,'.',''))
  from my_table  
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
1

One straightforward way is to use replacements to count the number of dots:

SELECT
    userid,
    LENGTH(userid) - LENGTH(REPLACE(userid, '.', '')) AS count
FROM yourTable;

Demo

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

The "." is a character which can be counted as any other character like "A", "7", " ". So you need to tell MySQL query which character name you want to count from a string.

See the code below:

SELECT 
      (CHAR_LENGTH(userid) - CHAR_LENGTH(REPLACE(userid, '.', ''))) AS count
FROM table_name;

For more details refer the link below Get count of zeros in an integer using MySQL

Nikolai Shevchenko
  • 7,083
  • 8
  • 33
  • 42