使用一系列 UNIONed 查询:-
(SELECT TimeStamp, FwdHr, W
FROM Meter_Data
WHERE TimeStamp Between 1356908255 AND 1356944255
AND MeterID = @meterID
AND DeviceID = @deviceID
ORDER BY TimeStamp
LIMIT 1)
UNION
(SELECT TimeStamp, FwdHr, W
FROM Meter_Data
WHERE TimeStamp BETWEEN 1356911855 AND 1356947855
AND MeterID = @meterID
AND DeviceID = @deviceID
ORDER BY TimeStamp
LIMIT 1)
UNION
(SELECT TimeStamp, FwdHr, W
FROM Meter_Data
WHERE TimeStamp BETWEEN 1356915455 AND 1356951455
AND MeterID = @meterID
AND DeviceID = @deviceID
ORDER BY TimeStamp
LIMIT 1)
UNION
(SELECT TimeStamp, FwdHr, W
FROM Meter_Data
WHERE TimeStamp BETWEEN 1356919055 AND 1356955055
AND MeterID = @meterID
AND DeviceID = @deviceID
ORDER BY TimeStamp
LIMIT 1)
UNION
(SELECT TimeStamp, FwdHr, W
FROM Meter_Data
WHERE TimeStamp BETWEEN 1356922655 AND 1356958655
AND MeterID = @meterID
AND DeviceID = @deviceID
ORDER BY TimeStamp
LIMIT 1)
您可能需要更改参数名称并根据您的数据库类多次传递它们
另一种可能性(但未经测试)是有一个子选择来获取仪表 ID/设备 ID 的每个范围内的最大时间戳,添加一个 CASE 语句来获取一行是哪个范围并按此分组,然后将结果加入反对主表。
请注意,如果仪表 ID/设备 ID 组合存在重复的时间戳,则这将无法正常工作。
不知道这会更快还是更慢!
SELECT Meter_Data.TimeStamp, Meter_Data.FwdHr, Meter_Data.W
FROM Meter_Data
INNER JOIN (SELECT MAX(TimeStamp) AS MaxTimestamp, MeterID, DeviceID,
CASE
WHEN TimeStamp Between 1356908255 AND 1356944255 THEN 1
WHEN TimeStamp BETWEEN 1356911855 AND 1356947855 THEN 2
WHEN TimeStamp BETWEEN 1356915455 AND 1356951455 THEN 3
WHEN TimeStamp BETWEEN 1356919055 AND 1356955055 THEN 4
WHEN TimeStamp BETWEEN 1356922655 AND 1356958655 THEN 5
END AS GroupNo
FROM Meter_Data
WHERE (TimeStamp Between 1356908255 AND 1356944255
OR TimeStamp BETWEEN 1356911855 AND 1356947855
OR TimeStamp BETWEEN 1356915455 AND 1356951455
OR TimeStamp BETWEEN 1356919055 AND 1356955055
OR TimeStamp BETWEEN 1356922655 AND 1356958655)
AND MeterID = @meterID
AND DeviceID = @deviceID
GROUP BY MeterID, DeviceID, GroupNo) Sub1
ON Meter_Data.MeterID = Sub1.MeterID
AND Meter_Data.DeviceID = Sub1.DeviceID
AND Meter_Data.TimeStamp = Sub1.MaxTimestamp
ORDER BY Meter_Data.TimeStamp