Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL group_concat() ordering by case statement values

In a MySQL group_concat() clause, I'm trying to order the resulting values of a case statement. The following query configuration properly orders things.name but does not order the 'Non-US' or 'Unknown' values within the same context.

SELECT 
  things.id
  ,group_concat(DISTINCT 
    CASE
    WHEN things.name <> 'United States' THEN 'Non-US'
    WHEN things.name IS NULL THEN 'Unknown'
    ELSE things.name
    END
  ORDER BY name SEPARATOR ', ')
FROM things
GROUP BY things.id

I want to do something like this, but it's not working:

SELECT 
  things.id
  ,group_concat(DISTINCT 
    (CASE
    WHEN things.name <> 'United States' THEN 'Non-US'
    WHEN things.name IS NULL THEN 'Unknown'
    ELSE things.name
    END) AS new_name
  ORDER BY new_name SEPARATOR ', ')
FROM things
GROUP BY things.id

Is there a way to sort by "new_name" without using sub-queries/ nested queries?

like image 473
s2t2 Avatar asked Sep 12 '25 12:09

s2t2


1 Answers

You can accomplish this by ordering by column position instead of column name.

For your case ORDER BY 1 should work.

SELECT 
  things.id
  ,group_concat(DISTINCT 
    CASE
    WHEN things.name <> 'United States' THEN 'Non-US'
    WHEN things.name IS NULL THEN 'Unknown'
    ELSE things.name
    END
  ORDER BY 1 SEPARATOR ', ')
FROM things
GROUP BY things.id
like image 155
Ike Walker Avatar answered Sep 15 '25 03:09

Ike Walker