簡體   English   中英

Oracle:基於同一表的不同行中的列數據的差值對記錄進行排序/排序

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM