我在努力寻找每个国家数量最高和最低的经销商

http://sqlfiddle.com/#!17/448f6/2

预期结果

"country"   "min_qty_name"  "max_qty_name"
1. "Madagascar" "Leonard Cardenas" "Gwendolyn Mccarty"
2. "Malaysia"   "Arsenio Knowles" "Yael Carter" 
3. "Palau"      "Brittany Burris" "Clark Weaver"  
4. "Tanzania"   "Levi Douglas" "Levi Douglas"

推荐答案

您可以通过一次排序完成这项工作,并按如下方式传递数据:

with min_max as (
  select distinct country, 
         first_value(distributor_name) over w as min_qty_name,
         last_value(distributor_name) over w as max_qty_name
    from product
  window w as (partition by country 
                   order by quantity
            rows between unbounded preceding
                     and unbounded following)
)
select * 
  from min_max
 order by min_max;

Updated Fiddle

Postgresql相关问答推荐

PostgreSQL散列连接与嵌套循环和散列索引

如何确定要与给定转储文件一起使用的pg_Restore版本?

GORM Golang SQL查询执行不区分大小写的搜索不起作用

自左联接的POSTGIS更新

Gorm 创建表单数据文件上传错误

PostgreSql maintenance_work_mem 在索引创建期间增加

Postgres 转储按顺序插入

PostgreSQL - 继承表的常见自动增量

当脚本工作时,Postgres now() 时间戳不会改变

使用 ON CONFLICT 从 INSERT 返回行,无需更新

包含受先前 DELETE 影响的行数的变量?

?(问号)运算符在 Rails 中查询 Postgresql JSONB 类型

如何在 PostgreSQL 中创建 guid

SQL:列为某个值时的唯一约束

使用 pg-promise 插入多条记录

子查询的自连接

Python PostgreSQL 模块.哪个最好?

Array Push的 Postgres 数组追加和数组长度

Postgresql:备份所有表 struct ,但只备份少数数据表

如何从我的 postgresql 查询中获取最小值、中值和最大值?