如何从重复数据中找出日期最后的一条???
tbgc_id是唯一值,不会重复
ass_segment1是物料号,可能会重复
std_item_id 是标准机号,会重复
表一
tbgc_id  ass_segment1   std_item_id    creation_date
56815    NB5E012        319055         2012-8-8 14:43:14
56816    RB51019        319055         2012-8-1 14:43:14  
56817    CC51019        319055         2012-7-1 14:43:14  
26810    QQ12123        101011         2012-6-1 14:43:14  
11810    GG22331        212100         2012-5-1 14:43:14  我要找出std_item_id重复的数据,
表二
tbgc_id  ass_segment1   std_item_id    creation_date
56815    NB5E012        319055         2012-8-8 14:43:14
56816    RB51019        319055         2012-8-1 14:43:14  
56817    CC51019        319055         2012-7-1 14:43:14 
再在表二中找出creation_date最近的这条数据:
表三
tbgc_id  ass_segment1   std_item_id    creation_date
56815    NB5E012        319055         2012-8-8 14:43:14我写的sql语句,只能得到表二,哪位能帮忙得到表三呢??????????????
(用select top得出的不算)select zth.tbgc_id,zth.ass_segment1,zth.std_item_id,zth.creation_date
  from zdoe_tbgc_head zth 
 where zth.std_item_id in
 (select std_item_id
    from zdoe_tbgc_head t
   where std_item_id = zth.std_item_id)

解决方案 »

  1.   

    你写的应该是得出的是所有的吧,而不是你说的三条
    26810 QQ12123 101011 2012-6-1 14:43:14   
    11810 GG22331 212100 2012-5-1 14:43:14 
    这两条应写有的
      

  2.   

    这个容易 得到表二后,多加一个字段 row_number()over(partition by std_item_id  order by 日期 desc) rn 求得rn为1的数据就行。
      

  3.   

    如果不明白,写出建表语句和插入数据语句,我写出具体sql。
      

  4.   


    --看下这个是不是你要结果
    select * from zdoe_tbgc_head zth 
    where creation_date=(select max(creation_date) 
    from zdoe_tbgc_head zth1 where zth.std_item_id=zth1.std_item_id);
      

  5.   

    使用 row_number()over() 就行。不明白,写出建表语句和插入数据语句,我再写具体sql
      

  6.   


    select zth.tbgc_id,zth.ass_segment1,zth.std_item_id,zth.creation_date
      from zdoe_tbgc_head zth  
     where zth.std_item_id in
     (select std_item_id
      from zdoe_tbgc_head t
      where std_item_id = zth.std_item_id)
    --你这个sql应该不能找到重复的std_item_id的吧
     select * from (
      select tbgc_id,ass_segment1,std_item_id,creation_date,
      row_number()over(partition by std_item_id order by creation_date desc)
      rn from zdoe_tbgc_head where std_item_id=some(
      select std_item_id from zdoe_tbgc_head  group by std_item_id having count(1)>1
      )) where rn=1
     
      

  7.   

    select * from (
      select tbgc_id,ass_segment1,std_item_id,creation_date,
      row_number() over(partition by std_item_id order by creation_date desc) rn
      from zdoe_tbgc_head
    ) where rn = 1;