23

我有一个非常简单的每月通讯数据集:

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) 的 1 个时事通讯。

4

3 回答 3

59
select top 1 * from newsletters where IsActive = 1 order by PublishDate desc
于 2012-12-06T20:41:28.480 回答
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

您甚至可以使用选择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

于 2012-12-06T20:42:25.213 回答
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
    )
于 2012-12-06T21:06:10.013 回答