1

So I have the following table:

retailer    register    store
1           104         b
1           101         a
2           104         b
2           101         a
3           104         b
3           101         a

I am looking to query the table to get a result that looks like:

retailer  register  store  
1 _ 101, 104 _ a, b  
2 _ 101, 104 _ a, b  
3 _ 101, 104 _ a, b
1
  • 1
    Are your commas in the expected result meant to represent a column separator, or is it literally a string of all the results comma-separated? Commented Sep 29, 2016 at 19:52

2 Answers 2

2

You can use group_concat and group by

 select 
    retailer
 , group_concat(register ORDER BY registed ASC SEPARATOR ', ')
 , group_concat(store ORDER BY store ASC SEPARATOR ', ')
 from my_table 
 group by retailer 

and if you need the saparator you should use a concat

 select 
      concat ( retailer
      , '_'
      ,  group_concat(register ORDER BY registed ASC SEPARATOR ', ')
      , '_'
      , group_concat(store ORDER BY store ASC SEPARATOR ', '))
 from my_table 
 group by retailer 
Sign up to request clarification or add additional context in comments.

7 Comments

you result will be different
@RaminDarvishov . explain better
your result will be different order and without seperator
',' (comma) is default seperator but user want comma with space
@RaminDarvishov if this is what you need the asnwer is updated and also there is a '_' between the column .. concatenated
|
1

You can use group by and GROUP_CONCAT with ORDER BY and SEPERATOR

select retailer, 
GROUP_CONCAT(register ORDER BY register DESC SEPARATOR ', ') AS register, 
GROUP_CONCAT(store ORDER BY store DESC SEPARATOR ', ') AS store
from my_table 
GROUP BY retailer

retailer  register  store  
   1      101, 104   a, b  
   2      101, 104   a, b  
   3      101, 104   a, b

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.