我正在使用的数据没有主键,而是按TMC值和日期值分组。我想要做的是采取5分钟的纪元值,并将它们组合成一个15分钟的纪元,一次平均三个记录。因此,将纪元0,1,2平均在一起以获得新记录,然后3,4,5等等。这是一个示例表。我不知道如何正确格式化:
TMC DATE EPOCH TRAVEL_TIME_ALL_VEHICLES
113N04415 1012016 0 228
113N04415 1012016 1 228
113N04415 1012016 2 222
113N04415 1012016 3 224
113N04415 1012016 4 229
113N04415 1012016 5 223
我认为我接近这个代码,因为它适用于第一个记录,但第二个记录失败了:
select tmc, date, avg(Travel_TIME_ALL_VEHICLES) AS TRAVEL_avg
from (select I40_2016_ALL.*,
row_number() over (order by TMC, date, epoch) as rn
from I40_2016_ALL) I40_2016_ALL
where tmc = '113n04415' and date = '1012016'
group by TMC, DATE, floor((rn - 1) / 3)
ORDER BY TMC, DATE
答案 0 :(得分:0)
您可以像这样使用整数除法:
SELECT TMC, [DATE], EPOCH, AVG(TRAVEL_TIME_ALL_VEHICLES) AS TRAVEL_avg
FROM (
SELECT TMC, [DATE], TRAVEL_TIME_ALL_VEHICLES,
ROW_NUMBER() OVER (ORDER BY TMC, [DATE], EPOCH) AS rn
FROM I40_2016_ALL) AS t
GROUP BY TMC, [DATE], (rn -1)/ 3
ORDER BY TMC, [DATE]
此查询将行1,2,3
放在一个组中,将行4, 5, 6
放在下一组中,等等。
答案 1 :(得分:0)
类似的东西:
SELECT AVG(TRAVEL_TIME_ALL_VEHICLES)
FROM
(
SELECT TRAVEL_TIME_ALL_VEHICLES AS TRAVEL_TIME_ALL_VEHICLES
,(ROW_NUMBER() OVER (Order by EPOCH) + 2)/3 AS GroupID
FROM
YourTable
) AS d
GROUP BY d.GroupID
答案 2 :(得分:0)
select tmc, date, floor((epoch + 1) / 3) as part,
avg(Travel_TIME_ALL_VEHICLES) AS TRAVEL_avg
from I40_2016_ALL
where tmc = '113n04415' and date = '1012016'
group by TMC, DATE, floor((epoch + 1) / 3)
或者如果你想要每一行都有...
select tmc, date, floor((epoch + 1) / 3) as part,
avg(Travel_TIME_ALL_VEHICLES)
over (partition by TMC, DATE, floor((epoch + 1) / 3)) AS TRAVEL_avg
from I40_2016_ALL
where tmc = '113n04415' and date = '1012016'