Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the distinct records based on maximum date?

I'm working with Sql server 2008.i have a table contains following columns,

    Id,
    Name,
    Date

this table contains more than one record for same id.i want to get distinct id having maximum date.how can i write sql query for this?

like image 728
user2514925 Avatar asked Apr 28 '14 08:04

user2514925


People also ask

How do you find Max date records?

Select row with max date per user using MAX() function Another way to get the latest record per user is using inner queries and Max() function. Max() function, when applied on a column, gives the maximum value of that column.

How do I get the max date field in SQL?

How can I get max date and minimum date in SQL? The SQL MIN() and MAX() Functions The MIN() function returns the smallest value of the selected column. The MAX() function returns the largest value of the selected column.

Can you use max with dates SQL?

Can we use MAX function for date in SQL? MAX function works with “date” data types as well and it will return the maximum or the latest date from the table.


2 Answers

Use the ROW_NUMBER() function and PARTITION BY clause. Something like this:

SELECT Id, Name, Date FROM (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY Id ORDER BY Date desc) AS ROWNUM 
    FROM [MyTable]
) x WHERE ROWNUM = 1
like image 175
jeroenh Avatar answered Oct 02 '22 21:10

jeroenh


One way, using ROW_NUMBER:

With CTE As
(
    SELECT Id, Name, Date, Rn = Row_Number() Over (Partition By Id
                                                   Order By Date DESC)
    FROM dbo.TableName
)
SELECT Id --, Name, Date 
FROM CTE
WHERE Rn = 1

If multiple max-dates are possible and you want all you could use DENSE_RANK instead.

Here's an overview of sql-server's ranking function: http://technet.microsoft.com/en-us/library/ms189798.aspx

By the way, CTE is a common-table-expression which is similar to a named sub-query. I'm using it to be able to filter by the row_number. This approach allows to select all columns if you want.

like image 45
Tim Schmelter Avatar answered Oct 02 '22 23:10

Tim Schmelter