0

我写了一个查询

(SELECT TimeStamp, AVG(FwdHr), W 
 FROM Meter_Data 
 WHERE (TimeStamp Between 1370476500 AND 1370477100 AND DeviceID = '1' 
 GROUP BY MeterID ORDER BY TimeStamp) 
UNION 
(SELECT TimeStamp, AVG(FwdHr), W 
 FROM Meter_Data 
 WHERE TimeStamp Between 1370496006 AND 1370496606 AND DeviceID = '1' 
 GROUP BY MeterID ORDER BY TimeStamp)

我想从表中为两个时间戳之间的每个仪表 ID 选择 avg(FwdHr)

然后将其与具有不同时间间隔的相同查询联合

4

2 回答 2

0

查询中的括号是不平衡且不必要的。

于 2013-06-13T09:29:41.867 回答
0

ORDER BY并且GROUP BY只能应用于最终结果集,不能应用于中间结果。括号也是不必要的

SELECT * FROM
(
  SELECT TimeStamp, AVG(FwdHr), W 
  FROM Meter_Data 
  WHERE TimeStamp Between 1370476500 AND 1370477100 
  AND DeviceID = '1' 

  UNION 

  SELECT TimeStamp, AVG(FwdHr), W 
  FROM Meter_Data WHERE TimeStamp Between 1370496006 AND 1370496606 
  AND DeviceID = '1' 
) as myTable

GROUP BY myTable.MeterID 
ORDER BY myTable.TimeStamp

甚至更好:使用OR而不是UNION

SELECT TimeStamp, AVG(FwdHr), W 
FROM Meter_Data 
WHERE DeviceID = '1' 
AND (TimeStamp Between 1370496006 AND 1370496606 
    OR
     TimeStamp Between 1370476500 AND 1370477100 )

GROUP BY MeterID 
ORDER BY TimeStamp
于 2013-06-13T09:36:37.217 回答