ThiagoPXP
ThiagoPXP

Reputation: 5462

Group by words in a comma separated string

In MySQL, given the following table where Tags is a column that 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 could we get sum(Salary) for each word/tag in Tags? so the result would look like this?

Tag          TotalSalary
------------------------
Sales        9000
Marketing    8000
Finance      7000
HR           3000

Any help would be very appreciated. Thank you!

Upvotes: 0

Views: 320

Answers (1)

sgeddes
sgeddes

Reputation: 62831

While I'd highly recommend normalizing your data structure and not store comma delimited lists, here's one handy approach utilizing a "numbers" table:

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(tags, ',', n.n), ',', -1) value, sum(salary)
FROM tags CROSS JOIN 
(
   SELECT a.N + b.N * 10 + 1 n
     FROM 
    (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
   ,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
    ORDER BY n
) n
WHERE n.n <= 1 + (LENGTH(tags) - LENGTH(REPLACE(tags, ',', '')))
GROUP BY SUBSTRING_INDEX(SUBSTRING_INDEX(tags, ',', n.n), ',', -1)

This leverages substring_index and can support up to 100 delimited items - easy to adjust as needed. I've used this approach several times which works quite well -- I first saw it used in this post.

Upvotes: 1

Related Questions