Answer by poshest for Grouped LIMIT in PostgreSQL: show the first N rows for...
Since v9.3 you can do a lateral join select distinct t_outer.section_id, t_top.id, t_top.name from t t_outer join lateral ( select * from t t_inner where t_inner.section_id = t_outer.section_id order...
View ArticleAnswer by wildplasser for Grouped LIMIT in PostgreSQL: show the first N rows...
-- ranking without WINDOW functions -- EXPLAIN ANALYZE WITH rnk AS ( SELECT x1.id , COUNT(x2.id) AS rnk FROM xxx x1 LEFT JOIN xxx x2 ON x1.section_id = x2.section_id AND x2.name <= x1.name GROUP BY...
View ArticleAnswer by Dave for Grouped LIMIT in PostgreSQL: show the first N rows for...
New solution (PostgreSQL 8.4) SELECT * FROM ( SELECT ROW_NUMBER() OVER (PARTITION BY section_id ORDER BY name) AS r, t.* FROM xxx t) x WHERE x.r <= 2;
View ArticleAnswer by Kouber Saparev for Grouped LIMIT in PostgreSQL: show the first N...
Here's another solution (PostgreSQL <= 8.3). SELECT * FROM xxx a WHERE ( SELECT COUNT(*) FROM xxx WHERE section_id = a.section_id AND name <= a.name ) <= 2
View ArticleAnswer by Quassnoi for Grouped LIMIT in PostgreSQL: show the first N rows for...
SELECT x.* FROM ( SELECT section_id, COALESCE ( ( SELECT xi FROM xxx xi WHERE xi.section_id = xo.section_id ORDER BY name, id OFFSET 1 LIMIT 1 ), ( SELECT xi FROM xxx xi WHERE xi.section_id =...
View ArticleGrouped LIMIT in PostgreSQL: show the first N rows for each group?
I need to take the first N rows for each group, ordered by custom column. Given the following table: db=# SELECT * FROM xxx; id | section_id | name ----+------------+------ 1 | 1 | A 2 | 1 | B 3 | 1 |...
View ArticleAnswer by David Skinner for Grouped LIMIT in PostgreSQL: show the first N...
A lateral join is the way to go, but you should do a nested query first to improve performance on large tables.SELECT t_limited.*FROM ( SELECT DISTINCT section_id FROM t ) t_groups JOIN LATERAL (...
View Article
More Pages to Explore .....