Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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).

like image 952
stevebot Avatar asked Dec 06 '12 20:12

stevebot


People also ask

How do you select a row with maximum value?

MySQL select the row with maximum value in a column : MAX() function. This section will help us learn how to get the maximum value for a column and get the record details corresponding to it. Let us start by creating a table sales_details followed by inserting some records to it.

How do I select a maximum value in a column in SQL?

To find the max value of a column, use the MAX() aggregate function; it takes as its argument the name of the column for which you want to find the maximum value. If you have not specified any other columns in the SELECT clause, the maximum will be calculated for all records in the table.

Can we use Max on a column?

MAX can be used with numeric, character, and datetime columns, but not with bit columns.

What does Max () mean in SQL?

The MAX() function returns the largest value of the selected column.


3 Answers

select top 1 * from newsletters where IsActive = 1 order by PublishDate desc
like image 70
Adam Robinson Avatar answered Oct 22 '22 09:10

Adam Robinson


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

like image 15
Taryn Avatar answered Oct 22 '22 09:10

Taryn


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
    )
like image 2
Narsimha Avatar answered Oct 22 '22 09:10

Narsimha