[英]Oracle: Ordering/sorting records based on the difference value of a column data in different rows of same table
我有一个表error_event_table
,具有3列:
eventtime timestamp;
url varchar2(1024);
errorcount number(30);
表格中的数据超过300万,我需要根据给定开始时间和结束时间的errorcount列值的差值,找到前n(100)个URL。 例如:表数据如下
eventtime | url |errorcount
2018-01-29 10:20:00 | url1.com | 950
2018-01-29 10:25:00 | url1.com | 1000
2018-01-29 10:20:00 | url2.com | 100
2018-01-29 10:25:00 | url2.com | 400
2018-01-29 10:25:00 | url3.com | 500
2018-01-29 10:10:00 | url35.com | 500
当startTime = 2018-01-29 10:20:00和endTime = 2018-01-29 10:25:00作为输入传递给查询时,预期输出为:
eventtime | url |errorcount
2018-01-29 10:25:00 | url3.com | 500
2018-01-29 10:25:00 | url2.com | 400
2018-01-29 10:20:00 | url2.com | 100
2018-01-29 10:25:00 | url1.com | 1000
2018-01-29 10:20:00 | url1.com | 950
查询应基于给定的开始时间和结束时间(查询的输入)递减的错误计数数量的差对记录进行排序,并将结果限制为前100个。换句话说,查询应找到前100个URL,结束时间和开始时间的最大差值,并在开始时间和结束时间得到相应的URL记录。
URL可能仅存在于结束时间而不是开始时间,在这种情况下,开始时间错误计数应设为0。类似地,URL可能仅存在于开始时间,在这种情况下,diff将为负数,而i不需要这些-ve diff记录在我的结果中。
我尝试了两种方法,但无法获得继续进行下去的正确方法。
方法1:使用分组依据
SELECT url,
Max(eventtime),
Max(errorcount)
FROM error_event_table
WHERE eventtime IN ( To_date(:startTime, 'yyyymmddHH24MISS'),
To_date(:endTime, 'yyyymmddHH24MISS')
)
GROUP BY url
ORDER BY Max(errorcount)DESC;
方法2:使用自我联接
SELECT t2.url eurl,
t1.url surl,
t2.eventtime endtime,
t1.eventtime starttime,
( t2.errorcount - t1.errorcount ) diff
FROM error_event_table t1,
error_event_table t2
WHERE ( t1.eventtime = To_date(:startTime, 'yyyymmddHH24MISS')
OR t2.eventtime = To_date(:endTime, 'yyyymmddHH24MISS') )
AND t2.url (+) = t1.url
ORDER BY ( t2.errorcount - t1.errorcount ) DESC
请提供有关如何解决此问题的方法的输入。
如果我理解正确, lag()
使用lag()
:
select t.*,
(error_count -
lag(error_count, 1, 0) over (partition by url order by eventtime)
) as diff
from t
where <date conditions here>
order by diff desc;
编辑:
如果您只想要最大的URL,那么:
select t.*
from (select t.*, row_number() over (partition by url order by diff desc) as seqnum
from (select t.*,
(error_count -
lag(error_count, 1, 0) over (partition by url order by eventtime)
) as diff
from t
where <date conditions here>
) t
) t
where seqnum <= 100
order by diff desc;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.