使用 SQL 查询列值已更改的行
如何查明表中列值更改的实例?此查询允许识别特定列值已被修改的行。
为了说明这一点,请考虑下表:
Value Time 0 15/06/2012 8:03:43 PM 1 15/06/2012 8:03:43 PM * 1 15/06/2012 8:03:48 PM 1 15/06/2012 8:03:53 PM 1 15/06/2012 8:03:58 PM 2 15/06/2012 8:04:03 PM * 2 15/06/2012 8:04:08 PM 3 15/06/2012 8:04:13 PM * 3 15/06/2012 8:04:18 PM 3 15/06/2012 8:04:23 PM 2 15/06/2012 8:04:28 PM * 2 15/06/2012 8:04:33 PM
目标是选择标有星号的行,指示值变化。这对于确定与这些更改相关的时间间隔至关重要,可用于其他数据库查询。
解决方案:
使用窗口函数和实现 SQL 查询行号,我们得出所需的rows:
;WITH x AS ( SELECT value, time, rn = ROW_NUMBER() OVER (PARTITION BY Value ORDER BY Time) FROM dbo.table ) SELECT * FROM x WHERE rn = 1;
解释:
其他注意事项:
SELECT * FROM table WHERE value <> LAG(value) OVER (ORDER BY time);
DECLARE @x TABLE(value INT, [time] DATETIME) INSERT @x VALUES (0,'20120615 8:03:43 PM'),-- (1,'20120615 8:03:43 PM'),--* (1,'20120615 8:03:48 PM'),-- (1,'20120615 8:03:53 PM'),-- (1,'20120615 8:03:58 PM'),-- (2,'20120615 8:04:03 PM'),--* (2,'20120615 8:04:08 PM'),-- (3,'20120615 8:04:13 PM'),--* (3,'20120615 8:04:18 PM'),-- (3,'20120615 8:04:23 PM'),-- (2,'20120615 8:04:28 PM'),--* (2,'20120615 8:04:33 PM'); ;WITH x AS ( SELECT *, rn = ROW_NUMBER() OVER (ORDER BY time) FROM @x ) SELECT x.value, x.[time] FROM x LEFT OUTER JOIN x AS y ON x.rn = y.rn + 1 AND x.value <> y.value WHERE y.value IS NOT NULL;
通过利用 SQL 窗口函数的强大功能,此查询有效地检索列值发生更改的行,从而提供对数据波动的宝贵见解。
以上是如何识别列值已更改的 SQL 行?的详细内容。更多信息请关注PHP中文网其他相关文章!