Oracle 中的前 3 名和其余总和 SQL

Top 3 and the sum of the rest in Oracle SQL

假设我在 table 上的 GROUP BY 查询得到以下结果:

Name         Count(*)
Apple        6
Mango        3
Grape        8
Pomegranate  1
Strawberry   13

我怎样才能得到列出的前三个元素,并将其余元素总结成某个名称,例如 'Others'。类似如下。

Name         Count(*)
Strawberry   13
Grape        8
Apple        6
Others       4

这将在 Oracle 中完成。搜索使用 TOP 生成结果,这在 Oracle 中不可用。

这是一个完整的解决方案,包括 SQL fiddle:

WITH fruit_summary AS (
  SELECT fruit, cnt,
     RANK() OVER (ORDER BY cnt DESC) AS cnt_rank
  FROM (
    SELECT fruit, count(*) AS cnt
    FROM fruit_table
    GROUP BY fruit
  )
)
SELECT fruit, cnt
FROM (
  SELECT fruit, cnt, cnt AS val
  FROM fruit_summary
  WHERE cnt_rank <= 3
  UNION ALL
  SELECT 'Others', SUM(cnt), -1
  FROM fruit_summary
  WHERE cnt_rank > 3
)
ORDER BY val DESC

请注意,如果您有多个摘要行在前 3 行中的计数相同,则查询可以 return 超过 4 (3 + 1) 行。

WITH 子句按水果对来源 table 进行分组,并为每一行分配一个等级。然后使用生成的中间值 table 来显示前 3 名以及总结结果。

此解决方案应该适合您。您实际上可以在 window 函数中使用聚合:

WITH f1 AS (
    SELECT fruit_name, COUNT(*) AS fruit_cnt, RANK() OVER ( ORDER BY COUNT(*) DESC ) AS fruit_rank
      FROM fruits
     GROUP BY fruit_name
)
SELECT fruit_name, fruit_cnt, fruit_rank
  FROM f1
 WHERE fruit_rank <= 3
 UNION
SELECT 'Others' AS fruit_name, SUM(fruit_cnt) AS fruit_cnt, MAX(fruit_rank) AS fruit_rank
  FROM f1
 WHERE fruit_rank > 3
 ORDER BY fruit_rank

Please see SQL Fiddle Demo here.