24

I have a pretty simple dataset of monthly newsletters:

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

and etc.

The PublishDate is unique.

Result (based on above):

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

What I want is pretty simple. I just want the 1 newsletter that IsActive and PublishDate = MAX(PublishDate).

7
  • 1
    The other similar questions all appeared to be dealing with partitions of data and aggregating max value over those partitions. If someone finds this is TRULY a duplicate please mark it as such. Commented Dec 6, 2012 at 20:33
  • 2
    dude please explain your downvote. Commented Dec 6, 2012 at 20:34
  • So based on the sample, which one do you want to return? Commented Dec 6, 2012 at 20:35
  • 1
    which database are you using? Commented Dec 6, 2012 at 20:42
  • 1
    @Bohemian tsql implies mssql Commented Dec 6, 2012 at 20:42

3 Answers 3

58
select top 1 * from newsletters where IsActive = 1 order by PublishDate desc
Sign up to request clarification or add additional context in comments.

1 Comment

This did not work for me due to the "top 1" portion. I replaced "top 1 " with "", and appended "limit 1" to fix it.
15

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

Comments

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
    )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.