The idea is as follows - in the base table
id tag_id value time 1 1 12 12:14 2 1 12 12:15 3 2 11 12:13 I want to get one last entry for all tags. those. with id 2 and id 3
desc limit does not seem to fit, and group by seems not
The idea is as follows - in the base table
id tag_id value time 1 1 12 12:14 2 1 12 12:15 3 2 11 12:13 I want to get one last entry for all tags. those. with id 2 and id 3
desc limit does not seem to fit, and group by seems not
And id incremental? Then you can like this:
SELECT tv.* FROM ( SELECT tag_id ,MAX(id) tv_id FROM tags_values tv GROUP BY tag_id ) x INNER JOIN tags_values tv ON tv.id = x.tv_id If you start from time
SELECT tv.* FROM ( SELECT tag_id AS tv_tag_id, MAX(f_timestamp) AS tv_timestamp FROM data_view tv WHERE f_timestamp >now() - interval '5 minutes' GROUP BY tag_id) x LEFT JOIN data_view tv ON tv.f_timestamp = x.tv_timestamp AND x.tv_tag_id = tv.tag_id UPDATE
If this option is not suitable, then you can use LATERAL . It is in PostreSQL since 9.3
SELECT y.* FROM ( SELECT tag_id FROM tags_values GROUP BY tag_id ) x, LATERAL ( SELECT * FROM tags_values tv WHERE tv.tag_id = x.tag_id ORDER BY tv.time DESC LIMIT 1 ) y LATERAL - DonilAnother solution:
select * from ( select *, rank() OVER (PARTITION BY tag_id ORDER BY id DESC) from TABLENAME ) as foo where rank = 1 Source: https://ru.stackoverflow.com/questions/467044/
All Articles
group by, in my opinion, works great here too. Strange that you did not work ... Sql fiddler - ApInvent