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

后端 未结 3 735
暗喜
暗喜 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:45
    CREATE TABLE Tmax(Id INT,NAME VARCHAR(15),PublishedDate DATETIME,IsActive BIT)
    INSERT INTO Tmax(Id,Name,PublishedDate,IsActive)
    VALUES(1,'Newsletter 1','10/15/2012',1),(2,'Newsletter 2','11/06/2012',1),(3,'Newsletter 3','12/15/2012',0),(4,'Newsletter 4','1/19/2012',0)
    
    SELECT * FROM Tmax
    
    SELECT t.Id
            ,t.NAME
            ,t.PublishedDate
            ,t.IsActive
    FROM Tmax AS t
        WHERE PublishedDate=
        (
            SELECT TOP 1 MAX(PublishedDate)
            FROM Tmax
            WHERE IsActive=1
        )
    
    0 讨论(0)
  • 2020-12-09 16:50
    select top 1 * from newsletters where IsActive = 1 order by PublishDate desc
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题