如何获取最新阅读

时间:2019-02-21 09:28:06

标签: sql

DATA                RESULT      
A           B        C       A          B        C
REC1    21/02/2019  50      REC1    21/02/2019  50
REC1    20/02/2019  500     REC2    21/02/2019  89
REC2    21/02/2019  89              
REC2    20/02/2019  5000                

您好,尝试按B desc的顺序对前1个*进行排序,但它仅返回1条记录。如何获得两条记录,如RESULT所示?

预先感谢

2 个答案:

答案 0 :(得分:0)

使用大多数数据库支持的row_number()

   select * from 
   ( select *,row_number() over(partition by A order by B desc) rn
     from table_name 
   ) a where rn=1

或者您可以使用相关的子查询

  select t1.* from table_name t1
  where t1.B=( select max(B) from table_name t2 where t1.A=t2.A)

答案 1 :(得分:0)

您需要按a分组并加入主表:

select t.* from (
  select a, max(b) maxb
  from tablename
  group by a
) g inner join tablename t
on t.a = g.a and t.b = g.maxb

请参见demo