Skip to content
Advertisement

Aggregate data with date ranges

I have the following table (#CategoryWeight) where weight and factor values are stored for each category with date ranges. I need to aggregate / simplify this data, when possible, so that consecutive data ranges are combined into a wide range for the same values of weight and factor.

Expected result:

Advertisement

Answer

You have overlapping time periods. That makes any assumption about the data troublesome — because the same year could have different values on different rows (nothing in your question precludes this).

Hence, the approach that I recommend is to expand out the data and then recombine it into chunks where the values are the same. The following uses a recursive CTE to expand the data and then a gaps-and-islands trick to recombine it:

Here is a db<>fiddle.

I notice a few things about your data.

  • You are using float for some of the values. This is very dangerous, because two values might look the same but really differ by a very small amount. Use the decimal/numeric type instead, so what-you-see-is-what-you-get.
  • The year values are strings, when they should be integers. Use the proper data types!
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement