如何根据聚合元素的数量在LISTAGG()中打印不同的输出?是否可以在不进行额外的COUNT(*)查询的情况下获取数量大的合并元素?有一个示例DDL: create table shepherds ( SHEPHERD_ID NUMBER(19), SHEPHERD_NAME VARCHAR2(50 CHAR));create table sheeps ( SHEEP_ID VARCHAR2(10 CHAR), SHEEP_NAME VARCHAR2(50 CHAR), SHEEP_SHEPHERD_ID NUMBER(19));-- insert shepherdsinsert into shepherds VALUES (111, 'Asher');insert into shepherds VALUES (222, 'Joseph');insert into shepherds VALUES (333, 'Nicodemus');-- first shepherd (one sheep)insert into sheeps VALUES ('A', 'Mark', 111);-- second shepherd (two sheeps)insert into sheeps VALUES ('A', 'Andres', 222);insert into sheeps VALUES ('B', 'Jeffrey', 222);-- third shepherd (three sheeps)insert into sheeps VALUES ('B', 'Jeffrey', 333);insert into sheeps VALUES ('A', 'Andres', 333);insert into sheeps VALUES ('D', 'Andres', 333);现在,我想通过以下方式显示所有用新行分隔的绵羊名的牧羊人: SELECT SHEPHERD_NAME, (SELECT listagg(SHEEP_ID || ': ' || SHEEP_NAME, CHR(10)) WITHIN GROUP (ORDER BY SHEEP_ID) FROM SHEEPS WHERE SHEEP_SHEPHERD_ID = SHEPHERD_ID)FROM SHEPHERDS;结果是:http://sqlfiddle.com/#!4/881a7/3但是,我想为只有一只绵羊的那些牧羊人隐藏绵羊的身份证信。我尝试了以下方法: SELECT SHEPHERD_NAME, (SELECT listagg( CASE WHEN COUNT(*) > 1 THEN SHEEP_ID || ': ' ELSE '' END || SHEEP_NAME, CHR(10)) WITHIN GROUP (ORDER BY SHEEP_ID) FROM SHEEPS WHERE SHEEP_SHEPHERD_ID = SHEPHERD_ID)FROM SHEPHERDS;但是,我得到了错误: ORA-00978:没有GROUP BY的嵌套组函数 http://sqlfiddle.com/#!4/881a7/7如果只聚合一个元素,是否可以从LISTAGG()返回不同的字符串?如何在不降低Oracle 11g或更高版本的查询性能的情况下检测聚合元素的数量? 最佳答案 子查询中的条件表达式应满足您的要求:SELECT sh.SHEPHERD_NAME, (SELECT (CASE WHEN COUNT(*) = 1 THEN MAX(s.SHEEP_NAME) ELSE LISTAGG(s.SHEEP_ID || ': ' || s.SHEEP_NAME, CHR(10)) WITHIN GROUP (ORDER BY s.SHEEP_ID) END) as SHEEPS FROM SHEEPS s WHERE s.SHEEP_SHEPHERD_ID = sh.SHEPHERD_ID ) as SHEEPSFROM SHEPHERDS sh; Here是db 小提琴。 08-05 22:04