Skip to content
Advertisement

Group rows into range while also showing gap

I am in need of a database select query solution for transforming a series of breakdown details into a summarized version of it, possibly in a view. Consider the table below. It has a composite primary key of (PK_1, PK_2, PK_3, and SEQUENCE_NO).

Only including all records with the STATUS_CODE of “Y”, how can I present the records in such a way consecutive records, respective to their composite primary keys, form ranges of value (indicated by SEQUENCE_FROM and SEQUENCE_TO, see below) while showing a gap that may indicate of a missing row, or a row with a STATUS_CODE with a value other than “Y”?

I used MIN and MAX but obviously it wouldn’t accomodate showing the gap between ranges.

Advertisement

Answer

This is a gaps and islands problem. Here is one way to solve with ROW_NUMBER, using the difference in row numbers method:

screen capture of demo below

Demo

The crux of the logic being used here is that we form an on-the-fly group number for each island, within each PK_1, PK_2, PK_3 partition, by taking the difference between the sequence number and a ROW_NUMBER. This difference is guaranteed to always be unique for each island.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement