資料庫中取行最大值、最小值、平均值問題
阿新 • • 發佈:2019-02-03
專案中經常碰到需要在資料錶行中取最大值、最小值、平均值問題,SQL資料庫不支援此功能,所以我們需要轉換一下。比如說有以下表結構:
圖1資料庫表結構
我們需要選取出每個時間點(DateTime)每個裝置(PositionID)的所有數值(Value1,Value2,Value3,Value4)平均值、最大值、最小值,可採用如下方法:
select t.[datetime] as [DateTime], t.positionid as Positionid, max(t.value1) as MaxValue, min(t.value1) as MinValue, avg(t.value1) as AvgValue from (select [datetime], positionid, value1 from historydata union select [datetime], positionid, value2 from historydata union select [datetime], positionid, value3 from historydata union select [datetime], positionid, value4 from historydata) t where positionid in ( select positionid from 表 ) group by t.[datetime], [positionid] order by positionid, [datetime]