mysql - Group by words in a comma separated string -


in mysql, given following table tags column contains comma separated strings

id    name    salary    tags ---------------------------- 1     james   5000      sales, marketing 2     john    4000      sales, finance 3     sarah   3000      hr, marketing, finance 

how sum(salary) each word/tag in tags? result this?

tag          totalsalary ------------------------ sales        9000 marketing    8000 finance      7000 hr           3000 

any appreciated. thank you!

while i'd highly recommend normalizing data structure , not store comma delimited lists, here's 1 handy approach utilizing "numbers" table:

select substring_index(substring_index(tags, ',', n.n), ',', -1) value, sum(salary) tags cross join  (    select a.n + b.n * 10 + 1 n           (select 0 n union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9)    ,(select 0 n union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) b     order n ) n n.n <= 1 + (length(tags) - length(replace(tags, ',', ''))) group substring_index(substring_index(tags, ',', n.n), ',', -1) 

this leverages substring_index , can support 100 delimited items - easy adjust needed. i've used approach several times works quite -- first saw used in this post.


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

python - NameError: name 'subprocess' is not defined -