我知道有很多这样的主题。但是我找不到解决方案。也许除了Group之外还有其他方法。
我有这个查询
sh(script: "cp -r somedir/dir somedir/file.sh somedir/makefile .", label: "Copying Stuff")
结果:
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
。
但是必须有更好的方法吗?
答案 0 :(得分:3)
在Postgres中使用greatest-n-per-group,对distinct on()
的查询通常效率最高
select distinct on (id) *
from the_table
order by id, share desc;
答案 1 :(得分:1)
使用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;
答案 2 :(得分:0)
使用row_number()
select * from
(
select *, row_number() over(partition by id1 order by id2) as rn
from tablename
)A where rn=1