SQL Select when data changes

I would like to get an integer value in SQL Select, but only when the data changes, for example:

Table data:

50 50 50 52 50 30 30 35 30 30 60 65 60 60 

Now I would like to get this data:

 50 52 50 30 35 30 60 65 60 

Performing a separate request, this will not work for me, because it will retrieve:

 50 52 30 35 60 65 

Any ideas?

I work with Entity Framework and C #, so suggestions for their use will also be appreciated!

Thanks.

+7
c # sql entity-framework
source share
4 answers
 List<int> list=...; var result=Enumerable.Range(0, list.Count- 1) .Where(x=> x== list.Count-1 || list[x]!=list[x+1]) .Select(x=>list[x]); 
+3
source share

select the results in dbResults, then do

 var results = new List<int>(); foreach (var element in dbResults) { if(!results.Any() || results.Last() != element) { results.Add(element); } } 

int results will be listed without consecutive duplicates

you can check it on ideone

+3
source share

This method is basically similar to @wudzik, but instead of checking the list of results each time, it just stores the last int in a variable and instead checks it.

 var result = new List<int>(); int? previous; foreach (var number in data) { if(!previous.HasValue || number != previous.Value){ { result.Add(number); previous = number; } } return result 
+2
source share
 WITH cte as (--cte is your test data SELECT 1 id, 50 value UNION SELECT 2, 50 UNION SELECT 3, 50 UNION SELECT 4, 52 UNION SELECT 5, 50 UNION SELECT 6, 30 UNION SELECT 7, 30 UNION SELECT 8, 35 UNION SELECT 9, 30 UNION SELECT 10, 30 UNION SELECT 11, 60 UNION SELECT 12, 65 UNION SELECT 13, 60 UNION SELECT 14, 60 ), temp AS --temp numbers the rows ( SELECT id, value, ROW_NUMBER() OVER (ORDER BY id) rowno FROM cte ) SELECT t2.value FROM temp t1 INNER JOIN temp t2 ON t1.rowno = t2.rowno - 1 --join to the next row using rownumber AND t1.value <> t2.value --but only return different values 
+1
source share

All Articles