问题
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