简体   繁体   中英

SQL Select one row for each category type

I've the data in my table in following format.

id | person_id| category | value| updated_date
-----------------------------
 1 | p1       |race  | r1 | 2015-02-26
 2 | p1       |race  | r2 | 2015-02-26
 3 | p2       |race  | r3 | 2015-02-27
 4 | p2       | race | r1 | 2015-02-28
 5 | p1       | lang | l1 | 2015-02-26

Now, I'm filtering based on the person's id. I need following in the result set.

  1. I need a record for each category that exists for this person.
  2. If there is more than one record for a category, list the once that is updated last.
  3. If the updated dates are same, get the first one in the list.

For p1,

1 | p1       |race  | r1 | 2015-02-26
5 | p1       | lang | l1 | 2015-02-26

It's something like this. because id is not a group by field because it changes on every row you select the min(id) for the group by personid,category, value.

select min(id), personid, category, value, max(updated_date)
group by personid, category, value 
having Max(updated_date)     

/* min(id) is just to return the value of id 
for the row having max(update_date)  
having max(update_date) get's the highest date*/

I would suggest doing this with not exists :

select t.*
from table t
where not exists (select 1
                  from table t2
                  where t2.personid = t.personid and
                        t2.category = t.cateogory and
                        (t2.updated_date > t.updated_date or
                         t2.updated_date = t.updated_date and t2.id < t.id
                        )
                 );

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