使用 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中文網其他相關文章!