Select only unique consecutive lines in TSQL

There were a few previous questions ( 1 and 2 ) that were pretty close to what I was trying to do, but couldn't tease the answer.

In my case, I have data that may contain several consecutive duplicates, so starting with Martin did :

eg.

id      companyName
-------------------    
1       dogs ltd
2       cats ltd
3       pigs ltd
4       pigs ltd
5       pigs ltd
6       cats ltd
7       cats ltd
8       dogs ltd
9       pigs ltd

I want to return

companyName
-----------    
dogs ltd
cats ltd
pigs ltd
cats ltd
dogs ltd
pigs ltd

eliminating duplicate consecutive , but keeping unique values ​​in order. In all previous questions, using the functions of the leader and the detainee, this will look only forward or backward, avoiding three or more repeating consecutive values.

+4
source share
1

:

SELECT companyName
FROM
    (
        SELECT
            id
            , companyName
            , LEAD(companyName, 1, NULL) OVER (ORDER BY id) lead
        FROM yourTable
    ) Q
WHERE
    companyName <> lead
    OR lead IS NULL
ORDER BY id
+3

Source: https://habr.com/ru/post/1689708/


All Articles