如果我有这样的桌子
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.
我没有得到我想要的结果,所以我欢迎一点帮助。
如何使用聚合呢?
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()
创建相等大小的箱子,因此边界值可以分成多个箱子。