Friday, 29 July 2016

Mysql - count values from comma-separated field

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.

Answer:
SELECT SUM(LENGTH(textfield) - LENGTH(REPLACE(textfield, ',', '')) + 1) FROM tablename

For each row you want to know number values in comma separated field use below query




SELECT ID, textfield, CHAR_LENGTH(textfield) - CHAR_LENGTH(REPLACE(textfield, ',', '')) + 1) as total FROM table

0 comments:

Post a Comment