I need to insert a specific range of years and months into a table so I can relate some climate data to those dates. Just like the table bellow:
year | month |
---|---|
1961 | 1 |
1961 | 2 |
1961 | 3 |
1961 | … |
1961 | 12 |
… | … |
2019 | 12 |
I am a beginner to SQL so i’m having a hard time coding this. I’m using VSC connected to a PostgresSQL Server. Can anyone help me?
I tried searching for a sollution here in stackoverflow but couldn’t find it.
3
Answers
You can use a combination of generate_series() and extract():
Just set your start and end date (the timestamp) correct and generate_series() creates the entire list. Extract() gives you the year and the month.
it’s probably easier for beginner to use months like using CTE (the with part) than using generate_series directly
This generates all your years, and in each, it spawns the 12 months. DB<>Fiddle demo:
If you just need numbers of years and months, you don’t need the
date
/timestamp
that’s normally useful to account for varying month lengths, days of week, leap years, but if you showed how you plan to use these, it might turn out to be more helpful to generate actualdate
-type dates, not numbers representing them.