What is the method for converting one row to multiple rows in SQL Server?
In SQL Server, it is possible to use the UNPIVOT operation to transform one row of data into multiple rows of data. The UNPIVOT operation is the inverse of converting column data into row data.
Here is an example demonstrating how to use UNPIVOT to transform a single row of data into multiple rows of data.
Let’s say there is a table called employees, with the following fields:
You can use the following query to convert one row of data into multiple rows of data:
SELECT employee_id, column_name, value
FROM employees
UNPIVOT
(
value FOR column_name IN (first_name, last_name, salary)
) AS unpvt;
Running the above query will produce the following results:
In the UNPIVOT statement, the columns first_name, last_name, and salary are transformed into row data by specifying value FOR column_name IN (first_name, last_name, salary).