SQL or LINQ: how do I select records where only one paramater changes?

南楼画角 提交于 2020-02-16 12:21:09

问题


Say we have this list:

Id  IdRef   myColumn    anotherColumn
448    70      1            228
449    70      1            2s8
451    70      1            228
455    70      2            2a8
456    70      2            s28
457    70      2            28
458    70      3            v
459    70      3            28
460    70      4            22
461    70      3            54
462    70      4            45
463    70      3            s28

I need to select a list with a record everytime "myColumn" changes. So the result would be:

    Id  IdRef   myColumn    anotherColumn
448    70      1            228
455    70      2            2a8
458    70      3            v
460    70      4            22
461    70      3            54
462    70      4            45
463    70      3            s28

回答1:


This is a gaps and islands problem. In SQL, here is one approach to solve it using window functions:

select Id, IdRef, myColumn, anotherColumn
from (
    select t.*, lag(myColumn) over(partition by IdRef order by Id) lagMyColumn
    from mytable t
) t
where lagMyColumn is null or lagMyColumn <> myColumn

The inner query recovers the value of myColumn on the previous row, ordered by Id. Then the outer query filters on records where that value is different from the one on the current row.

Demo on DB Fiddle:

 id | idref | mycolumn | anothercolumn
--: | ----: | -------: | :------------
448 |    70 |        1 | 228          
455 |    70 |        2 | 2a8          
458 |    70 |        3 | v            
460 |    70 |        4 | 22           
461 |    70 |        3 | 54           
462 |    70 |        4 | 45           
463 |    70 |        3 | s28          


来源:https://stackoverflow.com/questions/60059433/sql-or-linq-how-do-i-select-records-where-only-one-paramater-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!