返回前 N 行并将剩余行汇总为一行 - oracle sql
我试图从查询中获取包含前 N 行的结果集,并将其余行汇总为一行。我提出了如下查询 - 我需要有关使用任何内置 Oracle sql 函数的建议,这些函数可以帮助解决这种情况并消除我在此 sql 中的大量冗余。
select label, count_id from
(
select table1.NAME as label, count(table1.id) as count_id,
ROW_NUMBER() OVER (order by count(table1.id) desc) AS rn
from table1
where table1.NAME like 'D%'
group by table1.NAME
)
where rn <= 9 -- get top 9 rows
union
select 'Other' as label, sum(count_id) as count_id from
(
select label, count_id from
(
select table1.NAME as label, count(table1.id) as count_id,
ROW_NUMBER() OVER (order by count(table1.id) desc) AS rn
from table1
where table1.NAME like 'D%'
group by table1.NAME
)
where rn > 9 -- get rows after row-num 9
)
如果您对改进此查询有任何建议,请分享。
I am trying to get a result set with the top N rows from the query, and have the remaining rows rolled up into a single row. I have come up with a query as below - i am needing suggestions about using any built-in oracle sql functions that can help with this scenario and eliminate a lot of the redundancy i have in this sql.
select label, count_id from
(
select table1.NAME as label, count(table1.id) as count_id,
ROW_NUMBER() OVER (order by count(table1.id) desc) AS rn
from table1
where table1.NAME like 'D%'
group by table1.NAME
)
where rn <= 9 -- get top 9 rows
union
select 'Other' as label, sum(count_id) as count_id from
(
select label, count_id from
(
select table1.NAME as label, count(table1.id) as count_id,
ROW_NUMBER() OVER (order by count(table1.id) desc) AS rn
from table1
where table1.NAME like 'D%'
group by table1.NAME
)
where rn > 9 -- get rows after row-num 9
)
please share if you have any suggestions on improving this query.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这似乎是说明 子查询重构的教科书案例。
以下是我的建议:
在我的数据库表中,我尝试了这个,实际上我也得到了成本改进 - YMMV。
This appears to be a textbook case for illustrating subquery refactoring.
Here are my suggestions:
On the table in my database I tried this on I actually got a cost improvement as well - YMMV.
@DCookie 的答案的另一种变化可以尝试:
Another variation on @DCookie's answer to try: