1

I have two tables A and B.

A has an id for rows in table B, and a counter:

b_id  integer not null references B(id),
count integer not null default 1

Is there a way in Postgres to return query of A with the rows in B where the rows are repeated count times?

1

1 Answer 1

2

Yes. Use generate_series():

select t.*, n
from t cross join lateral
     generate_series(1, t.count, 1) gs(n);

The above is actually the verbose way of writing the logic. I prefer the above, because it is quite explicit about what is happening. However, you can simplify this to:

select t.*, generate_series(1, t.count, 1) as n
from t;
Sign up to request clarification or add additional context in comments.

2 Comments

So basically something like select B.* from A join B on A.b_id=B.id, generate_series(1, A.count,1) n
@Rob . . . I would never countenance the comma in the from clause. Use an explicit cross join. But that should work.

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.