17

I have to do some statics from read-only db where value are stored in a weird form

example: I have 2 rows like

ID    text field 
1     1001,1003,1004 
2     1003, 1005

I need to be able to count that this is "5".

I don't have write access so don't know how to read and count right away without creation a function or something like that.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
annvio
  • 175
  • 1
  • 1
  • 5
  • take a look at my [question](http://stackoverflow.com/questions/14184529/how-to-convert-comma-seperated-column-into-rows-and-add-counter). There is a satisfying answer – Muhammad Raheel Jan 31 '13 at 20:37

7 Answers7

33

Clever solution here on SO: How to count items in comma separated list MySQL

LENGTH(textfield) - LENGTH(REPLACE(textfield, ',', '')) + 1

EDIT

Yes you can select it as an additional column: and correcting with the CHAR_LENGTH from @HamletHakobyan's answer:

SELECT 
  ID, 
  textfield, 
  (CHAR_LENGTH(textfield) - CHAR_LENGTH(REPLACE(textfield, ',', '')) + 1) as total 
FROM table
Community
  • 1
  • 1
Matthew
  • 9,851
  • 4
  • 46
  • 77
10
SELECT SUM(LENGTH(textfield) - LENGTH(REPLACE(textfield, ',', '')) + 1)
  FROM tablename
zerkms
  • 249,484
  • 69
  • 436
  • 539
9

There is a small but significant omission in all answers. All will work only if database character set is utf8 or so, i.e. where symbol , gets one byte. The fact that the LENGTH function returns number of bytes instead of chars. Right answer is to use CHAR_LENGTH which returns number of characters.

SELECT
   SUM(CHAR_LENGTH(textfield) - CHAR_LENGTH(REPLACE(textfield, ',', '')) + 1) cnt
FROM yourTable
Hamlet Hakobyan
  • 32,965
  • 6
  • 52
  • 68
0

You could use something like this:

select sum(total) TotalWords
from
(
  select length(`text field`) - length(replace(`text field`, ',', '')) + 1 total
  from yourtable
) x

See SQL Fiddle with Demo

Taryn
  • 242,637
  • 56
  • 362
  • 405
0

All is wrong and doesn't works for me. The only one that work is this bellow

SELECT (length(`textfield`) - length(replace(`textfield`, ',', '')) + 1) as my
FROM yourtable;

This is my fiddle

http://sqlfiddle.com/#!9/d5a8e1/10

DiCaprio
  • 823
  • 1
  • 7
  • 24
  • 1
    don't u think, this is wrong of saying "All is wrong !!!".A lot may have change in `6` years. please review your answer. – Ankish Bansal Jan 22 '19 at 18:40
0
SELECT (LENGTH(column_name) - LENGTH(REPLACE(column_name, ',', '')) + 1) as value_count
  FROM table_name

Here LENGTH(column_name) - LENGTH(REPLACE(column_name, ',', '')) gives the number of commas in the value of each column. And +1 with this value provides the number of values separated by comma.

Armali
  • 18,255
  • 14
  • 57
  • 171
0

If someone looking for a solution to return 0 for empty fields.

IF(LENGTH(column_name) > 0, LENGTH(column_name) - LENGTH(REPLACE(column_name, ',', '')) + 1, 0)