获取具有列的最大值的行+同一行中同一列的最小值

时间:2017-09-05 20:33:49

标签: sql oracle group-by

我检查了以下问题:

GROUP BY with MAX(DATE)

Fetch the row which has the Max value for a column

  

列:account_number,app_guid,time_event_published(纪元时间)。

我希望每个app_guid的最新一行为account_number个最新time_event_published的{​​{1}}个account_number,每个app_guid代表另一列SELECT id, account_number, app_guid, time_event_published , <oldest_time_event_published_for_2152331553409959696> FROM ( SELECT id, account_number, app_guid, time_event_published, RANK() OVER (PARTITION BY app_guid ORDER BY time_event_published DESC) dest_rank FROM event where account_number=2152331553409959696 ) where dest_rank = 1; 最新一行。

ASC

我只能想到使用DB Entries: 2152331553409959696, TEST-ONE-APP_GUID, 25-JAN 2152331553409959696, TEST-ONE-APP_GUID, 1-JAN 2152331553409959696, TEST-TWO-APP_GUID, 25-FEB 2152331553409959696, TEST-TWO-APP_GUID, 1-FEB Required Result: 2152331553409959696, TEST-ONE-APP_GUID, 25-JAN, 1-JAN 2152331553409959696, TEST-TWO-APP_GUID, 25-FEB, 1-FEB 进行同一查询的其他数据库命中。有没有其他方法以及如何处理这一要求?

custom.js

2 个答案:

答案 0 :(得分:1)

如果我正确理解了您的问题,那么我认为以下SQL将满足您的要求:

SELECT id, account_number, app_guid, time_event_published , oldest_time_event_published FROM ( SELECT id, account_number, app_guid, time_event_published, RANK() OVER (PARTITION BY app_guid ORDER BY time_event_published DESC) dest_rank, MIN (time_event_published) OVER (PARTITION BY app_guid) oldest_time_event_published FROM event where account_number=2152331553409959696 ) where dest_rank = 1;

让我知道它如何处理您的数据并让我们知道。

我没有使用样本数据进行测试,但我相信它会对你有用!

泰德。

答案 1 :(得分:0)

这应该有用,但它不是很吸引人,它是否比两次击中表更好取决于性能和可读性。

SELECT  MAX(CASE WHEN dest_rank = 1 THEN id
                 ELSE NULL
             END
           ) AS id,
        MAX(CASE WHEN dest_rank = 1 THEN account_number
                 ELSE NULL
             END
           ) AS account_number,
        app_guid,
        MAX(CASE WHEN dest_rank = 1 THEN time_event_published
                 ELSE NULL
             END
           ) AS time_event_published,
        MAX(CASE WHEN dest_rank_asc = 1 THEN time_event_published
                 ELSE NULL
             END
           ) AS earliest_time_event_published
  FROM (SELECT id, 
               account_number, 
               app_guid, 
               time_event_published,
               RANK() OVER 
                 ( PARTITION BY app_guid 
                        ORDER BY time_event_published DESC
                 ) dest_rank,
               RANK() OVER 
                 ( PARTITION BY app_guid 
                       ORDER BY time_event_published ASC
                 ) dest_rank_asc,
          FROM event 
         WHERE account_number=2152331553409959696
        ) 
 GROUP
    BY app_guid;
相关问题