0

i have a table

enter image description here

and i have a range from '2019-01-02' to '2019-01-04'

I need to generate ID and DATES (generated) from my table which started_at and ended_at (nullable) between the given range

result must be like this:

enter image description here

ID 4 from table is not included in result because it's started_at and ended_at not in range '2019-01-02' and '2019-01-04'

I need query that will do that in postgres.

1
  • 1
    Sample data is better presented as formatted text. See here for some tips on how to create nice looking tables. Commented Apr 9, 2020 at 9:48

2 Answers 2

1

Use generate_series()

select t.id, g.dt::date
from the_table t
  cross join generate_series(t.started_at::date + 1,
                             least(t.ended_at::date, date '2019-01-04'),
                             interval '1 day') as g(dt)
where t.started_at >= date '2019-01-02' 
  and t.started_at < date '2019-01-04';
Sign up to request clarification or add additional context in comments.

2 Comments

I have an error: function generate_series(date, date) does not exist
@RIPOL92: sorry, forgot the third parameter
0

Worked this variant:

select t.id, g.dt::date from the_table t 
cross join generate_series(t.started_at::date + 1, 
 least(t.ended_at::date, date '2019-01-04'), interval '1 day') as g(dt) 
where dt >= date '2019-01-02' and dt < date '2019-01-04';

Comments

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.