sql - 如何使用每个 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.
我没有得到我想要的结果的知识,所以欢迎我提供一点帮助。
解决方案
只使用聚合怎么样?
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。
推荐阅读
- sql - 我正在尝试调整 SQL 查询以获得更好的性能
- postman - 如何从 Postman 请求中读取文件名
- visual-studio - QtCreator 到 VS2015 的快捷方式
- sql-server - 导出 blob 需要哪些权限
- laravel - 使用 Laravel 进行 API 版本控制和身份验证
- notepad++ - Notepad++:在现有变量行之间添加几行
- c# - 服务器重启后,Kestrel 绑定端口失败
- postgresql - Postgresql - 如何修复时间戳中的无效小时?
- github - 使用 svn-client 签出 github 文件夹,svn 更新无法正常工作
- php - 使用 Gedmo Tree 重新排序嵌套集树