简体   繁体   中英

selecting the first and the last row of partition orderd by date

hi u have a data set that looks like this在此处输入图像描述

i need to write a query to return the first and last color that each person selected. this is my code

    Select t1.name,t1.color,min(t1.rnkmin) ,t2.color,max(t2.rnkmax) 
    From(
   Select name,color,
  Danse_rank() over(partition by name order by time asc) as rnkmin 
  From table 3) as t1 inner join (
 Select name,color,
 Danse_rank() over (partition by name order by date asc) as rnkmax 
  From table 3) as t2 on t1.name=t2.name 

but sadly i get an error and i dont understand why thank you for the help:)

You can use row_number() twice:

select color, name, time
from (
    select
        t.*,
        row_number() over(partition by name order by time) rn_asc,
        row_number() over(partition by name order by time desc) rn_desc
    from mytable t
) t
where rn_asc = 1 or rn_desc = 1

If you want both colors in the same record, then you can aggregate:

select 
    name, 
    max(case when rn_asc = 1 then color end) as first_color
    max(case when rn_desc = 1 then color end) as last_color
from (
    select
        t.*,
        row_number() over(partition by name order by time) rn_asc,
        row_number() over(partition by name order by time desc) rn_desc
    from mytable t
) t
where rn_asc = 1 or rn_desc = 1
group by name

In many databases, the fastest method will use correlated subqueries:

select t.*
from t
where t.time = (select min(t2.time)
                from t t2
                where t2.name = t.name
               ) or
      t.time = (select max(t2.time)
                from t t2
                where t2.name = t.name 
               ) ;

You want an index on (name, time) .

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