简体   繁体   中英

MySQL GROUP_CONCAT() Treat First Value Differently Than Others

I'm not sure if this is possible, but I'm struggling to create a "path" of items in a GROUP_CONCAT() select without thinking of using a MIN() which I know I can't do.

Sample Data

  • ID : [1, 1, 1, 2, 2]
  • Number : [1, 2, 3, 2, 3]
  • Leg : [AB, BC, CD, EG, GZ]

I'd like to have results like this for ID 's 1 and 2 :

  • ID , Path
  • 1 , ABCD
  • 2 , EGZ

and I'm currently using the following GROUP_CONCAT()

SELECT ID, GROUP_CONCAT(CASE WHEN Number = 1 THEN Leg ELSE RIGHT(Leg, 1) END SEPARATOR '-') 
Path FROM my_table GROUP BY ID;

but this doesn't work when the Number column for an ID doesn't start at 1. I'd ideally like to start it at the MIN() of the Number within and ID but I can't do that. Is there anyway to conditionally do it on the first value in the GROUP_CONCAT() ?

You can do something like this:

SELECT ID,
       CONCAT_WS('-',
                 SUBSTRING_INDEX(GROUP_CONCAT(LEFT(Leg, 1) ORDER BY NUMBER), ',', 1),
                 GROUP_CONCAT(RIGHT(Leg, 1) ORDER BY NUMBER SEPARATOR '-') 
                )
FROM my_table
GROUP BY id;

Note: Your query should have the separator in it as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM