使用列上的MAX()值选择一行

时间:2012-12-06 20:32:44

标签: sql sql-server tsql

我有一个非常简单的月度简报数据集:

id  | Name          | PublishDate   | IsActive
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

等。

PublishDate是唯一的。

结果(基于上述):

id  | Name          | PublishDate   | IsActive
2   |  Newsletter 2 | 11/06/2012    |     1  

我想要的很简单。我只想要一份IsActive和PublishDate = MAX(PublishDate)的新闻通讯。

3 个答案:

答案 0 :(得分:55)

select top 1 * from newsletters where IsActive = 1 order by PublishDate desc

答案 1 :(得分:15)

您可以使用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

请参阅SQL Fiddle with Demo

您甚至可以使用选择max()日期的子查询:

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

请参阅SQL Fiddle with Demo

答案 2 :(得分:2)

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
    )