In Oracle, you can use the listagg function with the "order by" clause to convert multiple rows into one row. This statement can sort the data and then splice the sorted results together. The syntax is "listagg (column name) ,'separator') within group(order by column name)".
The operating environment of this tutorial: Windows 10 system, Oracle 11g version, Dell G3 computer.
Due to the need, the sub-organizations under the obtained organization need to be combined into one row of data, and Oracle’s own function is used
listagg (column name, 'separator') within group (order by column name)
That is, within each group, LISTAGG sorts the columns according to the order by clause, and sorts The final results are spliced together
My organizational structure is a tree structure, and the following SQL queries the names of all sub-departments under the current department.
SELECT LISTAGG(O.ORGNAME,',') WITHIN GROUP(ORDER BY LEVEL) FROM ORGANIZATION O START WITH O.ORGID = 1000 CONNECT BY PRIOR O.ORGID = O.PID AND LEVEL<4
Note: The above SQL uses the Oracle keyword LEVEL, which indicates which level the data in the tree structure is at
The above SQL also uses the Oracle tree query statement START WITH … CONNECT BY PRIOR …
If the query is for all parent nodes of the node, the above START WITH SQL should be changed to:START WITH O.ORGID = 1000 CONNECT BY PRIOR O.PID = O. ORGID
(The fields after PRIOR are not the same as the previous order)
ORGANIZATION table data is as follows
ORGID | ORGNAME | PID |
---|---|---|
Primary school | 0 | |
First grade | 1000 | |
Second grade | 1000 | |
101 class | 1100 | |
102 class | 1100 | |
103 class | 1100 | |
201Class | 1200 |
SELECT ORGNAME,LEVEL FROM ORGANIZATION START WITH ORGID = 1000 CONNECT BY PRIOR O.ORGID = O.PID
The execution results are as follows
LEVEL | |
---|---|
1 | |
2 | ##Second grade |
101 class | |
Class 102 | |
Class 103 | |
201Class | |
Elementary School , first grade, second grade, Class 101, Class 102, Class 103, Class 201
3. Put all the child nodes under the parent node into one line
SELECT LISTAGG(O.ORGNAME,',') WITHIN GROUP(ORDER BY LEVEL) FROM ORGANIZATION O START WITH O.ORGID = 1000 CONNECT BY PRIOR O.ORGID = O.PID AND LEVEL<4The execution results are as follows:
Elementary school, first grade, second grade, Class 101, Class 102, Class 103, Class 201
Recommended tutorial: "
Oracle Video Tutorial
The above is the detailed content of How to convert multiple rows to one in Oracle. For more information, please follow other related articles on the PHP Chinese website!