1

Is it possible to use e.g. in line like this

SELECT  trunc(dateadd(month,mon,add_months(date_trunc('month', CURRENT_DATE), -9))) as dates
FROM    months

instead of -9, I would like to have there maximum value of column created like this (so in this case 12):

with months as (
    select 1 as mon union all select 2 union all select 3 union all select 4 union all
    select 5 as mon union all select 6 union all select 7 union all select 8 union all
    select 9 as mon union all select 10 union all select 11 union all select 12

Is it possible somehow in Redshift? I tried just like that

SELECT  trunc(dateadd(month,mon,add_months(date_trunc('month', CURRENT_DATE), -MAX(mon))) as dates
FROM    months

but it is not working as expected

2
  • where is this mon field created? what if you create a column in the master table with the max value of the mon column and then use the resulting column in the function -- would that help? Commented Dec 15, 2021 at 12:31
  • What are you actually wanting to accomplish (as opposed to how you are trying to do it)? Are you wanting a date from 9 months ago? Can you describe the output you actually want to achieve? Commented Dec 16, 2021 at 3:13

1 Answer 1

1

Yes, an alternate way is

  With data as
  (Select row_number()  over (order by 1) rn from 
  table)
 Select datediff(month, max(rn), current_date) 
  from data;

You can take some bigger table having more entries as required and replace that tablename in WITH clause like you said max 9 in above case and just limit them to the count of your tables month entries

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

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.