SQL:获得限制的顶级产品?

时间:2014-11-10 05:31:44

标签: sql postgresql amazon-redshift

我可以获得这样的顶级产品:

SELECT productid, count(*) as total
FROM sales
JOIN product USING (productid)
GROUP BY productid
ORDER BY total DESC
LIMIT 10;

但是,我希望获得前9个产品,其中第10个包含前10个未包含的所有产品的总和。这可能是单个SQL语句(不使用多个调用,子查询,UNION还是WITH)?

我正在使用PostgreSQL(如果它在AWS Redshift中有效,则可获得奖励积分)。

编辑:我的最终问题是,这可以通过只扫描一次表来完成(这意味着所有额外的排序两次 - 这就是为什么你不能使用多个查询)?

2 个答案:

答案 0 :(得分:0)

试试这个。

SELECT TOP(10) productid, count(*)
FROM sales
JOIN product USING (productid)
GROUP BY productid

答案 1 :(得分:0)

不确定这是否符合"只扫描一次表"在你的眼里:

select case 
         when row_number() over w < 10 then productid 
         else null
       end as id,
       case 
         when row_number() over w < 10 then count_per_product 
         else total_products
       end as cnt
from (       
  select productid,
         count(*) as count_per_product,
         total_products
  from (
    SELECT productid, 
           count(*) over () as total_products
    FROM sales
  ) t
  group by productid, total_products
  order by count_per_product desc
) t
window w as (order by count_per_product desc)
order by case when 1 is null then 2 else 0 end desc nulls last
limit 10;

(由于您只使用productid列,我省略了产品表,因此没有理由包含products表。

SQLFiddle示例:http://sqlfiddle.com/#!12/313d3/2