Mar*_*rta 51 sql postgresql greatest-n-per-group
假设我有下一个数据
id date another_info
1 2014-02-01 kjkj
1 2014-03-11 ajskj
1 2014-05-13 kgfd
2 2014-02-01 SADA
3 2014-02-01 sfdg
3 2014-06-12 fdsA
Run Code Online (Sandbox Code Playgroud)
我想为每个id提取最后的信息:
id date another_info
1 2014-05-13 kgfd
2 2014-02-01 SADA
3 2014-06-12 fdsA
Run Code Online (Sandbox Code Playgroud)
我怎么能管理呢?
a_h*_*ame 97
最有效的方法是使用Postgres' distinct on
运算符
select distinct on (id) id, date, another_info
from the_table
order by id, date desc;
Run Code Online (Sandbox Code Playgroud)
如果您想要一个跨数据库工作的解决方案(但效率较低),您可以使用窗口函数:
select id, date, another_info
from (
select id, date, another_info,
row_number() over (partition by id order by date desc) as rn
from the_table
) t
where rn = 1
order by id;
Run Code Online (Sandbox Code Playgroud)
具有窗口函数的解决方案在大多数情况下比使用子查询更快.
Viv*_* S. 12
select *
from bar
where (id,date) in (select id,max(date) from bar group by id)
Run Code Online (Sandbox Code Playgroud)
在PostgreSQL,MySQL中测试过
小智 7
我发现这是最快的解决方案:
SELECT t1.*
FROM yourTable t1
LEFT JOIN yourTable t2 ON t2.tag_id = t1.tag_id AND t2.value_time > t1.value_time
WHERE t2.tag_id IS NULL
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
20997 次 |
最近记录: |