2013-02-15 76 views
0

我有一個PostgreSQL的查詢是這樣的:如何獲得查詢的前10個結果?

with r as (
    select 
     1 as reason_type_id, 
     rarreason as reason_id, 
     count(*) over() count_all 
    from 
     workorderlines 
    where 
     rarreason != 0 
     and finalinsdate >= '2012-12-01' 
) 
select 
    r.reason_id, 
    rt.desc, 
    count(r.reason_id) as num, 
    round((count(r.reason_id)::float/(select count(*) as total from r) * 100.0)::numeric, 2) as pct 
from r 
    left outer join 
     rtreasons as rt 
    on 
     r.reason_id = rt.rtreason 
     and r.reason_type_id = rt.rtreasontype 
group by 
    r.reason_id, 
    rt.desc 
order by r.reason_id asc 

這將返回結果的表4列:理由ID,與該原因ID相關聯的描述中,具有這個原因ID的條目的數量,並且該數字表示的總數的百分比。

此表是這樣的:

enter image description here

我想什麼做的是隻顯示基於關有原因ID條目總數的前10個結果。然而,不管剩下的是什麼,我想編入另一行,並加上一個名爲「其他」的描述。我將如何做到這一點?

回答

1
with r2 as (
    ...everything before the select list... 
    dense_rank() over(order by pct) cause_rank 
    ...the rest of your query... 
) 
select * from r2 where cause_rank < 11 
union 
select 
    NULL as reason_id, 
    'Other' as desc, 
    sum(r2.num) over() as num, 
    sum(r2.pct) over() as pct, 
    11 as cause_rank 
from r2 
where cause_rank >= 11 
+0

這個工作,但我不得不改變獲得職級的行: '等級() (通過計數(r.reason_id)desc)作爲cause_rank' – 2013-02-15 19:11:02

1

如上限值和跳繩和得到休息使用偏移說... Try This Site

+0

不好意思啊剛纔看到的PostgreSQL ......試圖回答這個快速 – idlehands23 2013-02-15 17:01:44

0

不確定Postgre但SELECT TOP 10 ...如果你排序正確

應該做的伎倆

但是關於第二部分:您可能會爲此使用正確加入。使用整個表格數據加入TOP 10結果,並僅使用未出現在左側的記錄。如果你計算出這些總和,你應該得到你的「休息總和」結果。

我假設vw_my_top_10是顯示前10條記錄的視圖。 vw_all_records顯示所有記錄(包括前10位)。

像這樣:

SELECT SUM(a_field) 
FROM vw_my_top_10 
RIGHT JOIN vw_all_records 
ON (vw_my_top_10.Key = vw_all_records.Key) 
WHERE vw_my_top_10.Key IS NULL 
相關問題