oracle sql: 收集聚合

oracle sql: collect aggregation

我想按属性对我的数据库条目进行分组,并同时知道每个组中有哪些条目。我使用 Oracle COLLECT 函数 COLLECT Function

收集分组条目的 ID
DECLARE
  TYPE ids_type IS TABLE OF number(19, 0);   
  ids ids_type;
BEGIN 
  select cast(collect(r.id) as ids_type) into ids from rechnungsdaten r group by r.status;
END;

但是我得到了错误:

Error report -
ORA-06550: Line 5, Column 44:
PL/SQL: ORA-00902: Invalid datatype
ORA-06550: Line 5, Column 5:
PL/SQL: SQL Statement ignored
06550. 00000 - "line %s, column %s:\n%s"
*Cause: Usually a PL/SQL compilation error.
*Action:

这里有什么问题?

您不能在 PL/SQL 匿名块中声明的类型上使用 COLLECT 函数。 您还有其他选择,例如

创建数据库类型并运行您的收集查询。

create or replace TYPE ids_type IS TABLE OF number(19, 0);
SELECT
    r.status,
    CAST(COLLECT(r.id) AS ids_type)
FROM
    rechnungsdaten r
GROUP BY
    r.status;

使用简单的 LISTAGG 查询以字符串形式查看 ID 列表

SELECT
    r.status,
    LISTAGG(r.id,',') WITHIN GROUP(
            ORDER BY
                id
        )
FROM
    rechnungsdaten r
GROUP BY
    r.status;

Demo