6

How to join two tables of sql and concatenate multiple rows into single cell?

The Query which i am using::

SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID;

Output which i got::

CustomerName          OrderId

John Doe                                     101

John Doe                                     102

John Doe                                     103

John Doe                                     104

Expected Output::

CustomerName          OrderId

John Doe                            101,102,103,104

1

3 Answers 3

1

Group concat is the easiest way to achieve the output you require.

Sign up to request clarification or add additional context in comments.

Comments

1

Use GROUP_CONCAT and aggregate by customer to generate a CSV list of orders:

SELECT
    c.CustomerName,
    GROUP_CONCAT(o.OrderID) AS OrderIDs
FROM Customers c
LEFT JOIN Orders o
    ON c.CustomerID = o.CustomerID
GROUP BY
    c.CustomerId;

Note that it would be preferable to aggregate by customer ID, if possible, because perhaps two or more customers have the same name.

Demo

Comments

0

Use group_concat

  SELECT Customers.CustomerName, group_concat(Orders.OrderID) as OrderID 
  FROM Customers LEFT JOIN Orders ON Customers.CustomerID=Orders.CustomerID
  group by Customers.CustomerName;

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.