我想從查詢中得到一個結果集的前N行,並有剩餘的行卷成一行。我想出了一個如下所示的查詢 - 我需要關於使用任何內置的oracle sql函數的建議,這些函數可以幫助解決這種情況,並消除我在這個sql中的大量冗餘。返回頂部N行,並有剩餘的行卷成一行 - oracle 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
)
請分享,如果您有任何關於改進此查詢的建議。
我喜歡塊使用的。在這種情況下非常合適。一個小小的改進......你應該將你的聯盟切換到聯盟所有,因爲這兩套之間不會有重複。 – Craig 2011-05-24 18:47:59
通常情況下,雖然在這種情況下總共只有10行, – DCookie 2011-05-24 18:50:13
@Craig @DCookie非常感謝您的建議 - 以及關於相關查詢成本的詳細信息。 – user12002221 2011-05-24 19:15:56