简体   繁体   中英

Group by column and get max and min id on sql

I got a table with theses Column: ID_REAL,DATE_REAL,NAME_REAL

I want to make a query to get result like this with a group by on the name

NAME | MAX(DATE_REAL) | ID_REAL of the MAX(DATE_REAL) | MIN(DATE_REAL) | ID_REAL of the MIN(DATE_REAL)

I dont know how to make it for the moment I have

select NAME_REAL,max(DATE_REAL),ID_REAL from MYREALTABLE group by NAME_REAL,ID_REAL
select NAME_REAL,min(DATE_REAL),ID_REAL from MYREALTABLE group by NAME_REAL,ID_REAL

But is not whats I need, and also I need only 1 query

Thanks you

I think the following should work by finding the records which have the minimum and maximum dates per name and joining those two queries.

select 
    mn.NAME_REAL,
    MIN_DATE_REAL,
    ID_REAL_OF_MIN_DATE_REAL,
    MAX_DATE_REAL,
    ID_REAL_OF_MAXDATE_REAL
from
(
    select NAME_REAL,
        DATE_REAL as MIN_DATE_REAL,
        ID_REAL as ID_REAL_OF_MIN_DATE_REAL,
        from (
        select 
            NAME_REAL, 
            ID_REAL, 
            DATE_REAL, 
            row_number() over (partition by NAME_REAL order by DATE_REAL asc) as date_order_asc 
        from MYREALTABLE
        )
    where date_order_asc = 1
) mn
inner join
(
    select NAME_REAL,
        DATE_REAL as MAX_DATE_REAL,
        ID_REAL as ID_REAL_OF_MAX_DATE_REAL,
        from (
        select 
            NAME_REAL, 
            ID_REAL, 
            DATE_REAL, 
            row_number() over (partition by NAME_REAL order by DATE_REAL desc) as date_order_desc 
        from MYREALTABLE
        )
    where date_order_desc = 1
) mx
 on mn.NAME_REAL = mx.NAME_REAL

You can join the two results into a single query result as follows

select o.NAME_REAL,o.max,o.id_real,t.min,o.id_real from (
select NAME_REAL,max(DATE_REAL) as max,ID_REAL, from MYREALTABLE group by NAME_REAL,ID_REAL)
as o inner join
(select NAME_REAL,min(DATE_REAL),ID_REAL from MYREALTABLE group by NAME_REAL,ID_REAL
) as t on o.NAME_REAL=t.NAME_REAL

Try the below -

select NAME_REAL,ID_REAL,max(DATE_REAL) as max_date, min(DATE_REAL) as min_date
from MYREALTABLE 
group by NAME_REAL,ID_REAL

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