SQL query case: convert a column to a row using UNION ALL.
After the conversion of rows and columns, you may encounter the need to replace columns.
Create table TestColRow (
Name VARCHAR (10 ),
East INT,
South INT,
West INT,
North INT
);
Insert into TestColRow
VALUES ('zhang san', 1, 2, 3, 4 );
Insert into TestColRow
VALUES ('Lee 4', 5, 6, 7, 8 );
Processing with UNION ALL
SELECT
Name, 'east' AS Place, east AS Value
FROM
TestColRow
UNION ALL
SELECT
Name, 'south' AS Place, south AS Value
FROM
TestColRow
UNION ALL
SELECT
Name, 'west' AS Place, West AS Value
FROM
TestColRow
UNION ALL
SELECT
Name, 'North' AS Place, north AS Value
FROM
TestColRow
Name Place Value
--------------------------
Zhang Weidong 1
Li sidong 5
Zhang sannan 2
Li Sinan 6
Zhang Sanxi 3
Li Sisi 7
Zhang sanbei 4
Li sibei 8
Unordered Processing
SELECT
ROW_NUMBER () OVER (order by (SELECT 0) AS id,
*
FROM
TestColRow
Unregister (Value FOR Place IN ([East], [South], [West], [North])
AS
Result:
Id name Value Place
---------------------
1 Zhang San 1 Dong
2 Zhang San 2 Nan
3 Zhang San 3 XI
4 sheets 3 4 north
5 Li Si 5 Dong
6 Li Si 6 Nan
7 Li Si 7 XI
8. Li Si 8 north