SQL为每个类别类型选择一行

时间:2015-02-27 19:19:18

标签: sql db2

我的表格中的数据采用以下格式。

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

现在,我根据此人的身份进行过滤。我需要在结果集中跟随。

  1. 我需要为此人存在的每个类别的记录。
  2. 如果某个类别有多个记录,请列出最后一次更新的记录。
  3. 如果更新日期相同,请获取列表中的第一个。
  4. 对于p1,

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

2 个答案:

答案 0 :(得分:0)

它是这样的。因为id不是按字段分组,因为它会在每行上更改,您可以按人物,类别,值选择组的分钟(id)。

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*/

答案 1 :(得分:0)

我建议您使用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
                        )
                 );
相关问题