0

I have the following code:

Select * from table
where to_date <= ( select max(to_date)
                  FROM table)
  and to_date >= (select (max(to_date)::date - interval '6 months')::date as to_date
                  FROM table) 

Basically, I am trying to look at all the results between the max date and then 6 months in the past, and I tried doing that by making 2 sub queries.

I seem to get null, but oddly enough, if add the regular date that

(select (max(to_date)::date - interval '6 months')::date

is giving and paste it as >='yyyy-mm-dd', the query seems to be working fine. It is weird as both sub-queries are actually spitting out date format results and have no idea why its giving this.

2
  • Why are you casting the value in the second query to a date but not in the first? Commented Aug 31, 2020 at 13:16
  • What do you mean "not working"? Commented Aug 31, 2020 at 14:10

2 Answers 2

1

You don't need both comparison:

select *
from table
where to_date >= (select (max(to_date)::date - interval '6 months')::date as to_date
                  from table
                 ) ;

This is assuming that the table reference is the same in both the inner and outer query.

Sign up to request clarification or add additional context in comments.

Comments

0

I can't really think of a reason why this wouldn't work, but you can rewrite the query to only run a single sub-query, which is also more efficient:

select t.*
from the_table t
  cross join (
    select max(the_date) as max_date
    from the_table
  ) mt
where t.to_date <= mt.max_date 
  and t.to_date >= mt.max_date - interval '6 months'

2 Comments

Weird enough with the approach you suggested I get the same null result (and no, it shouldn't be null, I do have data going back 6 months)
It can only be null if the table contains no rows at all.

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.