Oracle:分页LISTAGG()

envsm3lx  于 2023-04-05  发布在  Oracle
关注(0)|答案(1)|浏览(262)

我尝试从数据库中提取一组带引号的UUID,并使用LISTAGG()来完成此操作,因此:

SELECT
  COUNT(uuid) "Entries",
  '( ' || LSITAGG( DISTINCT '''' || uuid || '''', ', ' ON OVERFLOW ERROR ) || ' )' "UUIDs"
FROM
  table_with_uuids
/* 
WHERE
  criteria omitted for brevity
 */
;

这工作得很好,但也有一些用例,呈现的UUID的数量创建了一个太长的字符串(因此使用ON OVERFLOW ERROR)。在这些情况下,我想迭代LISTAGG()批量返回的结果。我觉得我这样做是正确的:

WITH active_uuids AS (
  SELECT DISTINCT
    uuid
  FROM
    table_with_uuids
  -- [ WHERE clause omitted ]
  OFFSET 0 ROWS FETCH NEXT 99 ROWS ONLY -- Fetching 100 will overflow LISTAGG
)
SELECT
  count(uuid) "Entries",
  '( ' || LISTAGG( '''' || uuid || '''', ', ' ON OVERFLOW ERROR ) || ' )' "UUIDs"
FROM
  active_uuids
;

但是我不想在记录用完之前手动递增OFFSET。理想情况下,我可以一次性获得所有返回记录的批量聚合列表。这可行吗?
(My对该数据库的访问受到限制;我不能CREATE视图,临时表,函数,或任何有趣的东西的原因)。

cxfofazt

cxfofazt1#

使用GROUP BY CEIL(ROWNUM/99)将UUID“分页”到99行的组中,然后聚合这些行。其他“页面”将在下一个组中,因此您将获得多行:

WITH active_uuids (uuid) AS (
  SELECT DISTINCT
         uuid
  FROM   table_with_uuids
  ORDER BY uuid             -- Optional
)
SELECT count(uuid) AS Entries,
       '( '
       || LISTAGG( '''' || uuid || '''', ', ' ) WITHIN GROUP (ORDER BY ROWNUM)
       || ' )' AS UUIDs
FROM   active_uuids
GROUP BY CEIL(ROWNUM/99);

fiddle

相关问题