In Oracle database, row conversion is a common data processing requirement. It converts multiple values in a row into multiple values in a column for better presentation and analysis of data.
For example, assume we have the following table:
ID | Name | Score1 | Score2 | Score3 |
---|---|---|---|---|
John | 80 | 70 | 90 | |
Lily | 90 | 85 | 95 | |
Tom | 60 | 75 | ##80 |
Subject | Score | ||
---|---|---|---|
Score1 | 80 | 1 | |
Score2 | 70 | 1 | |
Score3 | 90 | ##2 | Lily |
90 | 2 | Lily | |
85 | 2 | Lily | |
95 | 3 | Tom | |
60 | 3 | Tom | |
75 | 3 | Tom | |
80 | In Oracle, there are several Methods can be used to convert rows to columns, including using UNPIVOT and UNION ALL. Next, we will detail the steps and syntax of each method. |
CREATE TABLE score ( ID INT, Name VARCHAR2(20), Score1 INT, Score2 INT, Score3 INT ); INSERT INTO score VALUES (1, 'John', 80, 70, 90); INSERT INTO score VALUES (2, 'Lily', 90, 85, 95); INSERT INTO score VALUES (3, 'Tom', 60, 75, 80); COMMIT;Step 2: Run the UNPIVOT query Then, we can use the following UNPIVOT query to transform the data:
SELECT ID, Name, Subject, Score FROM score UNPIVOT ( Score FOR Subject IN (Score1, Score2, Score3) );The running results are as follows:
ID
Score | 1 | ||
---|---|---|---|
80 | 1 | John | |
70 | 1 | John | |
90 | ##2 | Lily | |
90 | 2 | Lily | |
85 | 2 | Lily | |
95 | 3 | Tom | |
60 | ##3 | Tom | Score2 |
3 | Tom | Score3 | |
Step 3: Clear the table | Finally, we can clear the data by deleting the table: |
CREATE TABLE score ( ID INT, Name VARCHAR2(20), Score1 INT, Score2 INT, Score3 INT ); INSERT INTO score VALUES (1, 'John', 80, 70, 90); INSERT INTO score VALUES (2, 'Lily', 90, 85, 95); INSERT INTO score VALUES (3, 'Tom', 60, 75, 80); COMMIT;Step 2: Run UNION ALL query Then, we can use the following UNION ALL query to transform the data:
SELECT ID, Name, 'Score1' Subject, Score1 Score FROM score UNION ALL SELECT ID, Name, 'Score2' Subject, Score2 Score FROM score UNION ALL SELECT ID, Name, 'Score3' Subject, Score3 Score FROM score ORDER BY ID, Subject;The running results are as follows:
ID
Name
##1 | John | ||
---|---|---|---|
1 | John | Score2 | |
1 | John | Score3 | |
2 | Lily | Score1 | |
2 | Lily | Score2 | |
2 | Lily | Score3 | |
3 | Tom | Score1 | |
##3 | Tom | Score2 | 75 |
3 | Tom | Score3 | 80 |
Step 3: Clear the table | Finally, we can clear the data by deleting the table: | Summary |
The above is the detailed content of How to convert rows to columns in Oracle. For more information, please follow other related articles on the PHP Chinese website!