我有一个包含列的表:起始日期,结束日期,ID, A, B, C(图片名称不同,但思路一致)
开始日期和结束日期跨越多个天,并包括每个小时的数据。此外,每个开始日期/结束日期都有多个ID。表的一个片段的示例:
http://i58.tinypic.com/300qsn4.png我想要做的是获取值C的每个ID的每日最大值,并在该每日最大值发生的行中保留其他值。
到目前为止,我是这样做的,但是对于这个非常大的数据集,这通常会超时:
select * from table
where (Startdate, Enddate, ID, A, B, C) not in(select * from table
where (ID, C) not in(select ID, max(C) from table group by ID));
您可以尝试使用row_number()
。假设您可以使用startdate
作为日期指示器:
select t.*
from (select t.*,
row_number() over (partition by id, trunc(startdate) order by c desc) as seqnum
from table t
) t
where seqnum = 1;
如果您需要获得时间跨度,我建议将数字连接以获得不同的日期,并连接以获得每个日期的值。例如,如果记录的时间跨度不超过9天:
with nums as (
select level - 1 as n
from dual
connect by level <= 10
)
select t.*
from (select t.*,
row_number() over (partition by id, trunc(startdate + n.n) order by c desc) as seqnum
from table t join
nums
on startdate + nums.n <= enddate
) t
where seqnum = 1;