1
create table t (a integer, b text);
insert into t values (1, 'a'), (2, 'a'), (3, 'a'), (10, 'b'), (11, 'b'), (0, 'c');

I need to limit select by 2 first groups of column b (1 - a, 2 - b);

select * from t order by b;
 a  | b 
----+---
  1 | a
  2 | a
  3 | a
 10 | b
 11 | b
 -- limit here
  0 | c
(6 rows)

Something like where b in (select distinct(b) from t order by b limit 2) whithout subquery.

4
  • Why "without subquery"? Commented Mar 21, 2019 at 10:42
  • Real case - b is not a table. It's a complex query with joins and filters. With subquery all filters applied to resultset twice. Like select top two auhtors and them books where book name like '%winter%'. Commented Mar 21, 2019 at 10:56
  • So, the column a- is it always incremental? How exactly do you know at what point to start counting for b? Commented Mar 21, 2019 at 11:51
  • Counting order by b. Values of a doesn't matter. Commented Mar 21, 2019 at 12:00

1 Answer 1

3

you can use windows functions like dense_rank :

select *,dense_rank()  over (order by  b) group_number from t order by b

so you can do :

select * from (
    select *,dense_rank() over (order by  b) group_number  from t order by b
) a where group_number<=2 
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly! Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.