如何在与原始 table 相同排序方式的列中查找连续的唯一值?

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

所以我有一个名为 IDTimeValues 的 table。 Values 列有多个相同的值。 Timedatetime2 数据类型,并且按唯一值的升序排列。 ID 也是具有 int 值的主键。 我希望结果作为 Values 列的连续唯一值,其顺序与原始 table.

中出现的顺序相同

我尝试使用 window 函数 LeadValues 列的给定值中查找下一个值,但我不确定如何找到唯一的下一个值。

原版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

由于带有 ID 4 的 "A" 没有与 ID 1 的 "A" 相继出现,所以我希望它出现在我的结果中。因此我想要如下结果。

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

试试下面这个-

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

其实你只需要过滤掉与上一行[值]相同的行。 如果您的 [id] 列不是连续的,那么您需要使用 ROW_NUMBER() 函数来生成连续的行 ID 并加入它。

    WITH TABLE_TEST AS (
    SELECT 1 AS ID, CAST('2019-06-24 18:23:04.0400000' AS DATETIME2) AS Time, 'A' AS [VALUE] UNION
    SELECT 2 AS ID, CAST('2019-06-24 18:23:04.0420000' AS DATETIME2) AS Time, 'A' AS [VALUE] UNION
    SELECT 3 AS ID, CAST('2019-06-24 18:23:04.0450000' AS DATETIME2) AS Time, 'B' AS [VALUE] UNION
    SELECT 4 AS ID, CAST('2019-06-24 18:23:04.0670000' AS DATETIME2) AS Time, 'A' AS [VALUE] UNION
    SELECT 5 AS ID, CAST('2019-06-24 18:23:04.0690000' AS DATETIME2) AS Time, 'C' AS [VALUE] UNION
    SELECT 6 AS ID, CAST('2019-06-24 18:23:04.0700000' AS DATETIME2) AS Time, 'C' AS [VALUE] 
)
SELECT
        t1.ID
       ,t1.Time
       ,t1.value    
    FROM TABLE_TEST t1
    LEFT JOIN TABLE_TEST t2
        ON t1.id = t2.id + 1
    WHERE t1.value<> ISNULL(t2.value, '')

将每一行与其前一行进行比较,如果 Value 的值相同,则忽略当前行。 t1.ID = 1 因为第一行将始终在输出中。

select  
    * 
from 
    TableTest t1, TableTest t2 
where 
    t1.ID = 1 or
    (t1.ID - 1 = t2.ID and
    t1.Value != t2.Value)