Artemii Artemii - 7 months ago 17
SQL Question

How to select data from one row in sql as table?

I have simple table:

| Val1 | Val2 |
--------------------------
| 10 | 20 |
--------------------------
| 20 | 30 |
--------------------------


How to select data from one row in this and get result as table where data in first column will be column name from original table and data in second column will be data from row?
Like this:

| Name | value |
----------------
| val1 | 10 |
----------------
| val2 | 20 |

Answer
CREATE TABLE #B
                       (VAL1 INT,
                       VAL2 INT
                       )
                       INSERT INTO #B VALUES(10,20),(20,30)

                       SELECT U.NAME, U.VALUE
FROM #B S
UNPIVOT
(
  VALUE
  FOR NAME IN (VAL1, VAL2)
) U;
Comments