分组但没有 select

Group by but no select

我知道有很多这样的话题。但我找不到解决方案。也许还有其他方式而不是组。

我有这个问题

Select id1, id2, share from table1

结果:

| id1   | id2  |   share    |
+-------+------+------------+
| 3864  | 3083 |   0.157223 |
| 3864  | 3095 |   0.007548 |
| 57695 | 3095 |   1        |
| 57749 | 2864 |   0.99516  |

我想要按 id1 分组的最高份额而不丢失 id2

所以它应该是这样的:

| id1   | id2  |   share    |
+-------+------+------------+
| 3864  | 3083 |   0.157223 |
| 57695 | 3095 |   1        |
| 57749 | 2864 |   0.99516  |

我可以这样做:group 仅通过 id1 并通过 id1 加入旧的 table 并共享以获得 id2.

但一定有更好的方法吗?

使用row_number()

select t.*
from (select t.*, row_number() over (partition by t.id1 order by t.share desc) as seq
      from table t
     ) t
where seq = 1;

PostgreSQL 中你可以使用 distinct on :

select distinct on (t.id) t.*
from table t
order by t.id, share desc;

使用row_number()

select * from
(
select *, row_number() over(partition by id1 order by id2) as rn
from tablename
)A where rn=1

在 Postgres 中查询 are typically most efficient using distinct on()

select distinct on (id) *
from the_table
order by id, share desc;