Assuming a data structure of the type
stock_name, action, start_date, end_date
google, growing, 1, 2
google, growing, 2, 3
google, falling, 3, 4
google, growing, 4, 5
yahoo, growing, 1, 2
How can I aggregate it to merge consecutive time intervals?
The output would look like:
stock_name, action, start_date, end_date
google, growing, 1, 3
google, falling, 3, 4
google, growing, 4, 5
yahoo, growing, 1, 2
I thought of using rank window function to number the consecutive with a constant and then grouping by that and action/name, but I cannot quite get it to work, something as below:
stock_name, action, start_date, end_date, rank
google, growing, 1, 2, 1
google, growing, 2, 3, 1
google, falling, 3, 4, 1
google, growing, 4, 5, 2
yahoo, growing, 1, 2, 1
If this were Mysql, I would easily solve it with variables, but this is not possible in postgres.
There could be any number of consecutive intervals, so self joining a predetermined nr of times is not an option.
Elegance(performance, readability) of solution matters.