SQL help: Repeat data for each month until no longer valid (Postgres)

Status
Not open for further replies.

lostnihilist

Ars Scholae Palatinae
1,436
I'm working on an ETL. I'd like to do this in a database because that's where the data is now. The only solutions I can think of involve pushing the data out and processing in a script. Can the hive mind do it in the db?

The data all come from flat files; so, there is only one table. The relevant attributes are id, score, score_date, file_date. The file_date is the date the file was generated. These file_dates range from every few months to a file per year and are of course are the same for large groups of id-scores. Though score_date is not consistent within a file_date.

The problem is that these records expire at some point, but there is no explicit row saying "id-score combination is no longer valid". So, I want to create a set of records for each month, starting with the earliest file_date or score_date. The id and score would be considered valid up until they change in some other record or until the next file_date. If the id is not found in the next file_date (the next file) it should be considered expired and no longer be reported.

My first thought is to create a file_date_table with two columns, file_date and month, where month is just consecutive months starting with file_date[_n] until file_date[_n+1] (though this kind of shifts the problem, as I'm not sure how to generate this sequential data like this in postgres). Then I would join the two tables based on the file_dates being equal, make sure the month of the score_date is at least as large as the month in the file_date_table, and the resulting


So, for relations:

  • scores(id, score, score_date, file_date) (note that I don't actually have a guaranteed key here. So, I will have to do some testing to make sure that doesn't mess anything up)
  • file_date_table(month, file_date) (month would be a key here)

The query would be something like:

Code:
SELECT s.id, s.score, s.score_date, s.file_date, f.month 
    FROM scores s 
    JOIN file_date_table f ON f.file_date=s.file_date
    WHERE date_trunc('month', s.score_date) >= f.month
;

I'm at a loss of how to generate the file_date_table though.
 
Status
Not open for further replies.