SQL获得前10名,其余分为两列

时间:2016-08-14 19:42:04

标签: sql sqlite

我对SQL查询有疑问,我无法挺身而出。我想将表格的前10个值中的SUM作为一列,将其余SUM作为另一列,以制作一个PIE图表,显示top10占整体的百分比:

我现在可以拿到剩下的或者排名前10但不是一排的摊位:

SELECT 
    SUM(counted) as Rest
FROM 
    Northeast 
WHERE 
    counted < (SELECT counted 
               FROM Northeast 
               ORDER BY counted DESC
               LIMIT 10)

任何解决方案?

1 个答案:

答案 0 :(得分:1)

大多数数据库都支持row_number(),因此您可以执行以下操作:

select sum(case when seqnum <= 10 then counted end) as top10_counted,
       sum(case when seqnum > 10 then counted else 0 end) as rest
from (select ne.*,
             row_number() over (order by counted) as seqnum
      from northeast ne
     ) ne;

编辑:

在SQLite中,你可以这样做:

select (select sum(counted) 
        from (select ne.* from northeast ne order by counted desc limit 10)
       ) as top10,
       (select sum(counted)
        from northeast
        where counted not in (select counted from northeast order by counted desc limit 10)
       ) as rest;

这是有效的,假设您与数据没有联系。

一个)我想不知道,上面的代码完成了工作:)