0

I am reviewing the functions but I cannot solve this one;

Write a function that returns every Friday 13th during a specific year.

Example:

SELECT * FROM martes13(2020);
13/01/2020
13/03/2020
13/08/2020

My unfortunate attempt, do not pay much attention.

DECLARE

diaInicial date;
diaFinal date;
anio1 date;
anio2 date;
auxData date;
dates date[];

BEGIN

diaInicial := ('01/' || '01/' || anio ) :: date;
diaFinal := diaInicial + '1 YEAR' :: interval;
anio2:= date_part('year',diaFinal);

FOR i IN 1..12 BY 1 LOOP
     FOR j IN 1..30 BY 1 LOOP
       diaInicial := anio || '-' || i || '-' || j;
       if(date_part('dom',auxData)==13 and date_part('dow',auxData)==5)then
          dates[j] := diaInicial;
       end if;
     end loop;
end loop;
return dates;
END;

There's no way to solve it no matter how hard I try, I understand that I have to use dates, years intervals and counters but it does not work out. Any help or information could be of use to me.

Thanks in advance.

1
  • Have a recursive cte that generates a calendar. SELECT from the cte, use WHERE to get 13 and Friday. Commented Jun 10, 2021 at 9:59

1 Answer 1

2

That can be solved with a simple SQL statement:

SELECT CAST(d AS date)
FROM generate_series(
        TIMESTAMP '2020-01-13',
        TIMESTAMP '2020-12-13',
        INTERVAL '1 month'
     ) AS thirteen(d)
WHERE EXTRACT (dow FROM d) = 5;

You could wrap that in an SQL function.

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.