如何获得查询的前10个结果?

时间:2013-02-15 16:53:55

标签: sql postgresql

我有一个像这样的postgresql查询:

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个结果。但是,无论剩下什么,我想编译成另一行,其中包含名为“Other”的描述。我该怎么做?

3 个答案:

答案 0 :(得分:1)

如上所述限制以及跳过和获取其余部分使用偏移量... Try This Site

答案 1 :(得分: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

答案 2 :(得分:0)

不确定Postgre但是选择TOP 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