Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL keep rows that include change in a subset of the columns

I have the following table

var1   | time   |  var2
------------------------
val1   |    1   |   a
val1   |    2   |   a
val1   |    3   |   a
val1   |    4   |   a
val2   |    5   |   a
val1   |    6   |   a
val3   |    1   |   b
val4   |    2   |   b
val4   |    3   |   b
val5   |    4   |   b

And I wish to remove all the rows with repeating values in var1 and var2 keeping changes in at least one of them. Sorry for the unclear explanation, instead, here is an example of how the desired table will be:

var1   | time   |  var2
------------------------
val1   |    1   |   a
val2   |    5   |   a
val1   |    6   |   a
val3   |    1   |   b
val4   |    2   |   b
val5   |    4   |   b

Lastly, is there a way to know how much space this table will take before executing the query?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

EDIT: fixing variables’ names in the tables

>Solution :

This is a gaps and islands problem, you could try the difference between two row numbers to solve it as the following:

WITH define_groups AS
(
  SELECT *,
    ROW_NUMBER() OVER (PARTITION BY var2 ORDER BY time) -
    ROW_NUMBER() OVER (PARTITION BY var1, var2 ORDER BY time) grp
  FROM table_name
),
row_numbering AS
(
  SELECT *,
    ROW_NUMBER() OVER (PARTITION BY var2, grp ORDER BY time) rn
  FROM define_groups
)
SELECT var1, time, var2
FROM row_numbering
WHERE rn = 1
ORDER BY var2, time

See demo.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading