我有下表:
deviceid year month value
432 2019 3 2571
432 2019 2 90
432 2019 1 314
432 2018 12 0
432 2018 11 100
437 2019 2 0
437 2019 1 1
437 2018 12 0
437 2018 11 3
437 2018 10 2
437 2018 9 0
437 2018 8 2
我需要一个查询,该查询为每个deviceId检索最近3个月的平均值。 例如:
deviceId Average
432 991.7
437 0.3
我很确定我必须使用分区或类似的东西。
我认为应该看起来像这样,但是我不知道如何获取最近3个月的平均值。
select deviceId, avg(value) from Table group by deviceid
答案 0 :(得分:1)
另一种选择是从您的year
和month
列计算日期以用于比较。
DECLARE @ComparisonDate DATE = '20190301';
--Or, perhaps, EOMONTH(GETDATE(),-1) to get the last day of last month?
SELECT
deviceId,
AVG(value) AS AvgValue
FROM
@t as t
WHERE
DATEFROMPARTS(year,month,1) >= DATEADD(MONTH,-3,@ComparisonDate)
GROUP BY
deviceId;
答案 1 :(得分:0)
您可以使用ROW_NUMBER来确定每个设备ID最近3个月是什么月份。
样本数据:
DECLARE @t TABLE (deviceid INT, year INT, month INT, value NUMERIC(12,2))
INSERT INTO @t VALUES
(432, 2019 , 3 ,2571),
(432, 2019 , 2 ,90 ),
(432, 2019 , 1 ,314 ),
(432, 2018 , 12,0 ),
(432, 2018 , 11,100 ),
(437, 2019 , 2 ,0 ),
(437, 2019 , 1 ,1 ),
(437, 2018 , 12,0 ),
(437, 2018 , 11,3 ),
(437, 2018 , 10,2 ),
(437, 2018 , 9 ,0 ),
(437, 2018 , 8 ,2 )
查询:
;WITH cte AS (
SELECT deviceid, value,
ROW_NUMBER() OVER (PARTITION BY deviceid ORDER BY year DESC, month DESC) rn
FROM @t
)
SELECT deviceid, AVG(value) average
FROM cte
WHERE rn BETWEEN 1 AND 3
GROUP BY deviceid
返回:
deviceid average
432 991.666666
437 0.333333