SELECT ONE Row with the MAX() value on a column

后端 未结 3 737
暗喜
暗喜 2020-12-09 16:22

I have a pretty simple dataset of monthly newsletters:

id  | Name          | PublishDate   | IsActive
1   |  Newsletter 1 | 10/15/2012    |     1
2   |  News         


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-09 16:58

    You can use row_number():

    select id, name, publishdate, isactive
    from
    (
      select id, name, publishdate, isactive,
        row_number() over(order by publishdate desc) rn
      from table1
      where isactive = 1
    ) src
    where rn = 1
    

    See SQL Fiddle with Demo

    You can even use a subquery that selects the max() date:

    select t1.*
    from table1 t1
    inner join
    (
      select max(publishdate) pubdate
      from table1
      where isactive = 1
    ) t2
      on t1.publishdate = t2.pubdate
    

    See SQL Fiddle with Demo

提交回复
热议问题