0

i have table like this

|  col1  |  col2  |  col3  |
|  a     |  1     |  g1    |
|  b     |  2     |  g1    |
|  c     |  3     |  g1    |
|  d     |  4     |  g2    |
|  e     |  5     |  g2    |
|  f     |  6     |  g2    |

i want to select them group by col3 column to get this result

g1: a1, b2, c3-g2: d4, e5, f6

i used

SELECT
  CONCAT(col3,":",GROUP_CONCAT(col1, col2))
FROM table
GROUP BY col3

to get rows like this

--------------
g1:a1,b2,c3
--------------
g2:d4,e5,f6
--------------

but i want to merge them into one string separated by dashes like this

g1:a1,b2,c3-g2:d4,e5,f6

2 Answers 2

3

Try the following, you can use another GROUP_CONCAT. Here is the demo.

select
  GROUP_CONCAT(ncol separator '-') as merged_rows
from
(
  SELECT
    CONCAT(col3,":",GROUP_CONCAT(col1, col2)) as ncol
  FROM table
  GROUP BY col3
) val

Output:

| merged_rows             |
| ----------------------- |
| g1:a1,b2,c3-g2:d4,e5,f6 |
Sign up to request clarification or add additional context in comments.

3 Comments

is this the only way to do it?
@JoeDoe cannot think of any other option but this would be the ideal way to achieve your output. :)
@JoeDoe . . . This is the simplest way to do this. I can imagine other methods, but this is the right way.
2

You can do this without a subquery. But the logic is rather complicated -- using json functions, window functions, and fixing up strings:

select col3, group_concat(col1),
       replace(replace(replace(json_unquote(json_arrayagg(concat(col3, ':', group_concat(col1))) over (order by col3)),
                               '["', ''
                              ), '"]', ''
                      ), '", "', '-'
              )
from t
group by col3
order by col3 desc
limit 1;

JSON is needed in order to "aggregate" the strings using a window function, to avoid the subquery. The logic would be a bit simpler if MySQL supported group_concat() (or the standard listagg()) as a window function.

Here is a db<>fiddle.

For instance, this is what the logic looks like in Postgres, which does support string aggregation as a window function.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.