Search code examples
sqlsql-servert-sqldistinct-values

How to find consecutive unique values in a column ordered in the same way as the original table?


So I have a table with name ID, Time and Values. Values column has multiple same values. Time is of datetime2 datatype and is in ascending order of unique values. ID is also a primary key with int values. I want the result as continuous unique values of Values column in the same order as it appears in the original table.

I have tried using window function Lead to find next values from a given value of Values column, but I am not sure how to find unique next values.

Original table "TableTest"

ID   Time                             Value
1    2019-06-24 18:23:04.0400000       A
2    2019-06-24 18:23:04.0420000       A
3    2019-06-24 18:23:04.0450000       B
4    2019-06-24 18:23:04.0670000       A
5    2019-06-24 18:23:04.0690000       C
6    2019-06-24 18:23:04.0700000       C

Since the "A" with ID 4 is not coming in continuation with the "A" of ID 1, I want it in my result. Hence I want the result as below.

ID   Time                             Value
1    2019-06-24 18:23:04.0400000       A
3    2019-06-24 18:23:04.0450000       B
4    2019-06-24 18:23:04.0670000       A
5    2019-06-24 18:23:04.0690000       C

Solution

  • Try this below-

    WITH your_table(ID,Time,Value)
    AS
    (
    SELECT 1,'2019-06-24 18:23:04.0400000','A' UNION ALL
    SELECT 2,'2019-06-24 18:23:04.0420000','A' UNION ALL
    SELECT 3,'2019-06-24 18:23:04.0450000','B' UNION ALL
    SELECT 4,'2019-06-24 18:23:04.0670000','A' UNION ALL
    SELECT 5,'2019-06-24 18:23:04.0690000','C' UNION ALL
    SELECT 6,'2019-06-24 18:23:04.0700000','C'
    )
    
    SELECT A.ID,A.Time,A.Value
    FROM
    (
        SELECT *, LAG(Value) OVER(ORDER BY ID)  Lag_Value
        FROM your_table
    )A
    WHERE value <> Lag_Value OR Lag_Value IS NULL