日期:2014-05-17 浏览次数:20733 次
--> 测试数据:[tb] IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb] GO CREATE TABLE [tb]([时间] DATETIME,[设备1] VARCHAR(7),[设备2] INT) INSERT [tb] SELECT '2012-9-30 20:00',100,420 UNION ALL SELECT '2012-9-30 21:00',110,430 UNION ALL SELECT '2012-9-30 22:00',120,440 UNION ALL SELECT '2012-9-30 23:00',142,445 UNION ALL SELECT '2012-10-1 00:00',210,449 UNION ALL SELECT '2012-10-1 1:00:00',200,500 UNION ALL SELECT '2012-10-1 2:00:00',300,200 UNION ALL SELECT '2012-10-1 3:00:00',345,550 UNION ALL SELECT '2012-10-1 4:00:00',352,0 UNION ALL SELECT '2012-10-1 5:00:00',160,610 --------------开始查询-------------------------- SELECT [时间],CASE WHEN [设备1]<(SELECT [设备1] FROM [tb] WHERE [时间]=DATEADD(hh,-1,t.[时间])) THEN (SELECT [设备1] FROM [tb] WHERE [时间]=DATEADD(hh,-1,t.[时间])) ELSE [设备1] END ,CASE WHEN [设备2]<(SELECT [设备2] FROM [tb] WHERE [时间]=DATEADD(hh,-1,t.[时间])) THEN (SELECT [设备2] FROM [tb] WHERE [时间]=DATEADD(hh,-1,t.[时间])) ELSE [设备2] END FROM [tb] AS t ----------------结果---------------------------- /* 时间 (无列名) (无列名) 2012-09-30 20:00:00.000 100 420 2012-09-30 21:00:00.000 110 430 2012-09-30 22:00:00.000 120 440 2012-09-30 23:00:00.000 142 445 2012-10-01 00:00:00.000 210 449 2012-10-01 01:00:00.000 210 500 2012-10-01 02:00:00.000 300 500 2012-10-01 03:00:00.000 345 550 2012-10-01 04:00:00.000 352 550 2012-10-01 05:00:00.000 352 610 */