首页 > 解决方案 > 如何使用每个 TILE 的最大值和该 TILE 中的项目数创建结果集

问题描述

如果我有这样的桌子

id product_name  price

1   product_1     5    
2   product_2     10 
3   product_3     100
4   product_4     200   
5   product_5     9000     

如果我执行这样的查询:

 select  price,  ntile(3) over(order by price) as rank from products order by price.

它将产生大致如下的结果:

   id  product_name   price       rank

    1   product_1     5             1
    2   product_2     10            1
    3   product_3     100           2
    4   product_4     200           2
    5   product_5     9000          3

但我想进一步扩展它并获得每个图块的最大值以及该图块上的元素数。

   price    items
    10       2
    200      2
    9000     1  // I think I won't use the last tile max value, but it's here anyway.

我没有得到我想要的结果的知识,所以欢迎我提供一点帮助。

标签: sqlmariadbpostgresql-9.6

解决方案


只使用聚合怎么样?

select max(price), count(*)
from (select price,  ntile(3) over (order by price) as rank
      from products
     ) p
group by rank
order by price

请注意: ntile()创建大小相等的 bin,因此边界值可能会拆分到多个 bin。


推荐阅读