依次不同

sequentially distinct

我有一个 table,其中包含一个时间和一个整数值,用于存储基于时间的机器使用情况。

示例:

Time    /   machine
11:00       1
12:00       2
13:00       2
14:00       1
15:00       5
16:00       5
17:00       1

要查找机器更改,我必须过滤连续且包含相同机器 ID 的行。现在,我通过选择所有行并在 while 循环中搜索机器更改来做到这一点。

我等的是;

Time    /   machine
11:00       1
12:00       2
14:00       1
15:00       5
17:00       1

有没有办法用 sql 或 tsql 做到这一点?我目前使用的是 2008 R2,但我打算使用更新的版本。

select * from tablebname t1
where t1.machine <> (select top 1 machine from tablename t2
                     where t2.time < t1.time
                     order by t2.time desc)

如果第 "before" 行在时间上具有同一台机器,则不要 return 这一行。

您可以使用LAG(从SQL Server 2012 开始可用)获取上一条记录的机器ID。然后,您可以在外部查询中将当前记录的 id 与上一条记录的 id 进行比较:

SELECT [Time], Machine
FROM (
   SELECT [Time], Machine, LAG(Machine) OVER (ORDER BY [Time]) AS PrevMachine
   FROM MachineTable ) m
WHERE (PrevMachine IS NULL) OR (machine <> PrevMachine)

请注意,您还需要谓词PrevMachine IS NULL,因为第一条记录没有以前的记录。

SQL Fiddle Demo here

对于 SQL Server 2008,上面的查询可以写成:

;WITH CTE AS (
SELECT [Time], Machine, ROW_NUMBER() OVER (ORDER BY [Time]) AS rn
FROM MachineTable
)
SELECT c1.[Time], c1.machine 
FROM CTE AS c1
LEFT JOIN CTE AS c2 ON c1.rn = c2.rn + 1
WHERE (c2.machine IS NULL) OR (c1.machine <> c2.machine)