SQL |列表
DBMS 中的 LISTAGG函数用于从数据库表的列中聚合字符串。
- 它使连接字符串变得非常容易。它类似于串联,但使用分组。
- 该函数的特殊之处在于,它还允许对串联列表中的元素进行排序。
句法:
LISTAGG (measure_expr [, 'delimiter']) WITHIN GROUP
(order_by_clause) [OVER query_partition_clause]
measure_expr : The column or expression to concatenate the values.
delimiter : Character in between each measure_expr, which is by default a comma (,) .
order_by_clause : Order of the concatenated values.
让我们有一个名为 Gfg 的表,其中有两列显示每个主题所属的主题名称和主题编号,如下所示:
SQL> select * from GfG;
SUBNO SUBNAME
---------- ------------------------------
D20 Algorithm
D30 DataStructure
D30 C
D20 C++
D30 Python
D30 DBMS
D10 LinkedList
D20 Matrix
D10 String
D30 Graph
D20 Tree
11 rows selected.
查询 1:使用 LISTAGG函数编写 SQL 查询,以在单个字段中输出主题名称,值以逗号分隔。
SQL> SELECT LISTAGG(SubName, ' , ') WITHIN GROUP (ORDER BY SubName) AS SUBJECTS
2 FROM GfG ;
输出:
SUBJECTS
-----------------------------------------------------------------------------------
Algorithm , C , C++ , DBMS , DataStructure , Graph , LinkedList , Matrix , Python ,
String , Tree
查询 2:编写一个 SQL 查询,对每个科目进行分组,并在 LISTAGG函数的帮助下,将每个科目以逗号分隔显示在其各自的部门中。
SQL> SELECT SubNo, LISTAGG(SubName, ' , ') WITHIN GROUP (ORDER BY SubName) AS SUBJECTS
2 FROM GfG
3 GROUP BY SubNo;
输出:
SUBNO SUBJECTS
------ --------------------------------------------------------------------------------
D10 LinkedList , String
D20 Algorithm , C++ , Matrix , Tree
D30 C , DBMS , DataStructure , Graph , Python
查询 3:编写一个 SQL 查询,在 LISTAGG函数的帮助下,按学科编号(SUBNO)排序显示属于每个部门的学科。
SQL> SELECT SubNo, LISTAGG(SubName, ',') WITHIN GROUP (ORDER BY SubName) AS SUBJECTS
2 FROM GfG
3 GROUP BY SubNo
4 ORDER BY SubNo;
输出:
SUBNO SUBJECTS
----- --------------------------------
D10 LinkedList, String
D20 Algorithm, C++, Matrix, Tree
D30 C, DBMS, DataStructure, Graph, Python