1

I have a field named "ColorCode" in a MySQL table that has values such as these:

28373 GYY green
23423 HH red
23423 HH green  
2343 QWE red    
SKDJF blue  
green

What would be the SQL statement to show how many occurances of each color, something like this PHP-influenced pseudo code:

SELECT COUNT(*) FROM products GROUP BY END(EXPLODE(ColorCode));
2
  • I hope you don't have a lot of those records.
    – Ja͢ck
    Nov 23, 2012 at 15:29
  • It's just a one time query so performance doesn't matter this time. Nov 23, 2012 at 15:30

2 Answers 2

4

fugly, but something like this

group by RIGHT(ColorCode, LOCATE(' ', REVERSE(ColorCode))

If you're running this query frequently, definitely consider splitting that 'last' value into its own field so you can at least index it. performance is going to be abysmal on large tables.

0
1

How about this:

GROUP BY SUBSTRING_INDEX(ColorCode,' ',-1);

This doesn't work for your last example though.

Evidently it does work for your last example too! :D

Here is a demonstration: http://sqlfiddle.com/#!2/d41d8/4088

1
  • SUBSTRING_INDEX('green', ' ', -1) == 'green'
    – Ja͢ck
    Nov 23, 2012 at 15:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.