简体   繁体   中英

Multiple group by query in DB2

I need to fetch particular records after comparison of two columns. Let me explain below.

Serial_number(VARCHAR2)     Process_date(DATE)       Process_Time(TIME)
----------------------------------------------------------------------
1                           2010-12-01               11:45:05     
1                           2010-12-01               12:45:05
1                           2010-12-01               14:45:05
2                           2010-10-01               10:45:05
2                           2010-11-01               09:45:05
3                           2009-12-01               11:45:05

I want result like below :-

Serial_number(VARCHAR2)     Process_date(DATE)       Process_Time(TIME)
-----------------------------------------------------------------------
1                           2010-12-01               14:45:05
2                           2010-11-01               09:45:05
3                           2009-12-01               11:45:05

If there are multiple rows of same Serial_number we need to fetch only those row which have latest Process_date. If in case Process_date is same then it should fetch those rows which have latest Process_Time (data type of this column is TIME).

Please help me to write query for this in DB2 database.

using the row_number() OLAP function can be helpful in cases like this:

with ranked_rows as (
    select row_number() over (
               partition by serial_number 
               order by process_date asc process_time desc
           ) rank,
           serial_number,
           process_date,
           process_time
       from table
) 
select serial_number,
       process_date,
       process_time
    from ranked_rows
    where rank = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM