Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Select with Concat_ws all type from group of record

Using SQL, I can do something like:

SELECT T1.ID AS ORDER_ID, T2.CODE AS CODE  
FROM SCHEMA.TABLE1 AS T1 
LEFT JOIN SCHEMA.TABLE2 AS T2 ON T1.ID = T2.O_ID

Output:

ORDER_ID    CODE 
-----------------
25005CM73   AB 
25005CM73   CD 
25005CM73   EF 
25CMMM074   CD 
25CMMM074   AB 
25CMMM074   EF 
25CMMB075   GH 
25CMMB075   IG 
25CMMB075   KL

I would like to return only 1 row for each ORDER_ID with CONCAT.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Expected output:

ORDER_ID    CODE 
--------------------
25005CM73   AB,CD,EF
25CMMM074   CD,AB,EF
25CMMB075   GH,IJ,KL

I don’t know how to write the code for a group of ORDER_ID.

>Solution :

Try this using GROUP_CONCAT:

SELECT 
  ORDER_ID,
  GROUP_CONCAT(CODE ORDER BY CODE SEPARATOR ',') as CODE
FROM
 (
  SELECT T1.ID AS ORDER_ID, T2.CODE AS CODE  
  FROM SCHEMA.TABLE1 AS T1 
  LEFT JOIN SCHEMA.TABLE2 AS T2 ON T1.ID = T2.O_ID
 ) as a
GROUP BY ORDER_ID;

Note: You can directly use GROUP_CONCAT in the query while joining instead of using sub-query.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading