分组依据,但没有选择

时间:2020-01-10 09:59:54

标签: sql postgresql greatest-n-per-group

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

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

3 个答案:

答案 0 :(得分:3)

在Postgres中使用,对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