我有一张这样的表:
[Date] [hour] [valid] [value] [type]
我需要对23个先前值及其自身(24个值)中的每个小时执行averange,并且仅当我有18个或更多有效值时才这样做。
我用这个查询做了一个小时:
select type, avg(value)
from table
where type = 10
and valid = 1
and ((date = '11/10/2016' and hour <= 22) or
(date = '11/09/2016' and hour > 22))
group by type
having count(*)>=18;
但我需要在该时间间隔内每小时的日期间隔。 有可能吗?
谢谢。
答案 0 :(得分:0)
您可以在下面写一下,我假设列valid
包含Y
和N
值。
select type
,max(avg1)
from (
select type
,avg(value) over (order by trunc(date,'HH') range between interval '24' hour preceding and interval '0' hour following ) as avg1
,count(decode(valid,'Y',1)) over (order by trunc(date,'HH') range between interval '24' hour preceding and interval '0' hour following ) as count1
from table
where type = 10
and valid = 1)
where count1 >= 18
group by type;
答案 1 :(得分:0)
抱歉,但与小时分开保存日期并不好。所以我将它合并到with
子句中的日期。如果您不希望这样,您可以在我to_date(date || ':' || hour, 'dd/mm/yyyy:hh24')
的任何地方使用d
并忽略with
条款
with dat as (select to_date(date || ':' || hour, 'dd/mm/yyyy:hh24') d, valid, value, type from table)
select d1.d, d1.type, avg(d2.value)
from dat d1 cross join dat d2
where d1.d < (d2.d + 1) and d1.d >= d2.d and d2.valid = 1
group by d1.d, d1.type
having count(*) >= 18;
我希望它能奏效。如果您提供了任何测试数据,我会测试它。