sql - Postgresql 按多个列进行分组并在每个组内进行排序

标签 sql postgresql sql-order-by distinct window-functions

我有一个包含以下列的表格:

<表类=“s-表”> <标题> order_id 金额 评分 百分比 customer_id ref_id doc_id <正文> 1 1000 1 0.6 112 8 5 2 2000 2 0.1 111 8 8 2 3000 3 0.2 110 8 6 3 4000 5 0.1 100 7 7 3 4000 2 0.7 124 7 9 3 5000 4 0.6 143 5 10 4 2000 6 0.4 125 4 11 4 2500 1 0.55 185 4 12 4 1000 4 0.42 168 5 13 4 1200 8 0.8 118 1 14

对于每个 order_id,我想找到具有最高金额、最高评级、最高百分比、最低 customer_id 的 doc_id。

对于单个订单 ID,我可以这样做:

select order_id, doc_id
from orders
where order_id = 1625
order by amount desc nulls last,
         rating desc nulls last, 
         percent desc nulls last,
         customer_id asc
limit 1;

但我无法完成所有订单。所以输出应该是这样的:

<表类=“s-表”> <标题> order_id doc_id <正文> 1 5 2 6 3 10 4 12

我正在使用 Postgresql。 知道我应该怎么做吗?

最佳答案

使用FIRST_VALUE()窗口函数:

SELECT DISTINCT order_id, 
       FIRST_VALUE(doc_id) OVER (
         PARTITION BY order_id 
         ORDER BY amount DESC NULLS LAST, rating DESC NULLS LAST, percent DESC NULLS LAST, customer_id
       ) doc_id
FROM orders;

请参阅demo .

关于sql - Postgresql 按多个列进行分组并在每个组内进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70670433/

相关文章:

sql - 如何仅按日期从 postgres 的时间戳列中选择?

mysql - 选择 '' -''是什么意思

PHP:如何处理 SQL 返回值?

postgresql - Postgres jsonb 使用更大的运算符在数组中搜索(使用 jsonb_array_elements)

c - Libpq 使用大量内存的简单示例

MySQL:按用户定义方式的查询排序

mysql - 对 SQL 中的一系列值进行计数

node.js - Node - 使用 node-postgres 设置 Postgres 驱动程序

java - Oracle 默认按行为排序

其他列的 SQL ORDER BY 行为?