如何使用每个TILE的最大值和该TILE中的itens数创建结果集

问题描述 投票:1回答:1

如果我有这样的桌子

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

但我想稍微扩展一下,获得每个图块的最大值和该图块上的itens数量。

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

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

sql mariadb postgresql-9.6
1个回答
0
投票

如何使用聚合呢?

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()创建相等大小的箱子,因此边界值可以分成多个箱子。

© www.soinside.com 2019 - 2024. All rights reserved.