我知道有很多这样的主题。但是我找不到这种解决方法。也许除了Group之外还有其他方法。
我有这个查询
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
和共享对旧表进行联接以获取id2
。
但是必须有更好的方法吗?
使用Postgres中的greatest-n-per-group,对distinct on()
的查询通常效率最高
distinct on()
使用select distinct on (id) *
from the_table
order by id, share desc;
:
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()