我有一个包含字段的表:
id
category_id
property_id
Weight
我怎样才能获得{category_id,property_id}的列表,其中property_id来自最高权重?
示例:
id | category_id | property_id | weight |
1 | 1 | 1 | 20 |
2 | 1 | 2 | 10 |
3 | 2 | 2 | 30 |
4 | 2 | 3 | 40 |
查询后的正确结果:
category_id | property_id
1 | 1 (because 20 > 10)
2 | 3 (because 40 > 30)
这是一个简单的问题,但我正在寻找最简单,最正确的方法,如何使用没有子查询和临时表的postgresql工具。
答案 0 :(得分:2)
使用distinct on
:
select distinct on (category_id) t.*
from tablewithfields t
order by category_id, weight desc;
编辑:
您可以使用窗口函数执行此操作,但上述内容可能更有效:
select t.*
from (select t.*, row_number() over (partition by category_id order by weight desc) as seqnum
from tablewithfields t
) t
where seqnum = 1;