Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Split Multiple Columns into Multiple Rows

I'm having difficulty with this problem.

I have a table with this structure:

OrderID | Manager   | Worker      
1       | John      | Sally       
2       | Tim       | Kristy       

I need a SQL query to get a result set like this:

OrderID | Employee       
1       | John           
1       | Sally    
2       | Tim 
2       | Kristy

Is this possible to perform?

like image 800
Kevin M. Avatar asked May 02 '12 14:05

Kevin M.


People also ask

How do I split multiple columns into multiple rows?

Click in a cell, or select multiple cells that you want to split. Under Table Tools, on the Layout tab, in the Merge group, click Split Cells. Enter the number of columns or rows that you want to split the selected cells into.

How do I split a single row into multiple rows in SQL Server?

I used STRING_SPLIT() which is a table valued function supports SQL server 2016 and higher versions. You need to provide the formatted string into this function and use cross apply to join and generate the desired output.

How do I separate one column into multiple columns in SQL?

sql. functions provide a function split() which is used to split DataFrame string Column into multiple columns.


2 Answers

Simplest way I can think of is (assuming you don't care if Tim is listed before or after Kristy):

SELECT OrderID, Employee = Manager FROM dbo.table
UNION ALL
SELECT OrderID, Employee = Worker FROM dbo.table
ORDER BY OrderID;

If order matters, and you want manager first always, then:

SELECT OrderID, Employee FROM
(
  SELECT r = 1, OrderID, Employee = Manager
  FROM dbo.Table
  UNION ALL
  SELECT r = 2, OrderID, Employee = Worker
  FROM dbo.table
) AS x
ORDER BY OrderID, r;
like image 114
Aaron Bertrand Avatar answered Nov 15 '22 08:11

Aaron Bertrand


You can use UNPIVOT for this.

SELECT p.OrderID, p.Employee
FROM (SELECT OrderID, Manager, Worker FROM table) a
UNPIVOT (Employee FOR FieldName IN (Manager, Worker)) p
like image 25
Anthony Faull Avatar answered Nov 15 '22 07:11

Anthony Faull