create temp table tmp_apps (
id integer
);
create temp table tmp_pos (
tmp_apps_id integer,
position integer
);
insert into tmp_apps
select 1 id union
select 2 id
;
insert into tmp_pos (tmp_apps_id, position)
select 1 tmp_apps_id, 1 as position union all
select 1 tmp_apps_id, 1 as position union all
select 1 tmp_apps_id, 2 as position union all
select 1 tmp_apps_id, 3 as position union all
select 1 tmp_apps_id, 3 as position union all
select 2 tmp_apps_id, 1 as position
;
/*
Expected result:
tmp_apps_id tmp_pos_position
1 1,2
2 1
*/
How to get first 2 comma separated, distinct tmp_pos.position for each tmp_apps.id
It is possible ?
This happens to be much like the solution @araqnid posted a bit faster than me.
CTE or subquery, that’s just two ways for doing the same in this case.
My version is different in one important aspect:
By using
GROUP BYinstead ofDISTINCTto get distinct values, you can apply the window functionrow_number()(key element for the solution) in the same query level and do not need another subquery (or CTE).The reason for this is that aggregation (
GROUP BY) is applied before window functions whileDISTINCTis applied after. In many situationsDISTINCTandGROUP BYoffer equally good solutions. In a case like this you can put the subtle difference to good use if you know it. I expect this to be quite a bit faster.