分组依据,但没有选择项

问题描述 投票:0回答:3

我知道有很多这样的主题。但是我找不到这种解决方法。也许除了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

但是必须有更好的方法吗?

sql postgresql greatest-n-per-group
3个回答
1
投票

使用Postgres中的,对distinct on()的查询通常效率最高

distinct on()

1
投票

使用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

0
投票

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

row_number()
© www.soinside.com 2019 - 2024. All rights reserved.