1

I have a table:

ID  Title   Date
30   1     10/10/2010
20   1     10/11/2010
40   2     01/01/2010

i need a way to select distinct titles with max dates.
so when title is 1, i should have the second row selected since the date in the 1st row is smaller than the date in the second row.
as a result the query should return:

20 1 10/11/2010
40 2 01/01/2010
3
  • Don't you mean 30 1 10/11/2010 ? Commented Nov 30, 2010 at 13:09
  • Your results set shows the ID of the first row with the date of the second. Is this what you want or a typo? Commented Nov 30, 2010 at 13:10
  • possible duplicate of stackoverflow.com/questions/121387/… Commented Nov 30, 2010 at 13:19

3 Answers 3

2

Your data set is unclear; do you want the minimum ID and the maximum date?

SELECT ID=MIN(ID), Title, [Date] = MAX([Date])
FROM Table
GROUP By Title

Or was it a typo, and you want the row with the maximum date (assuming that the dates may not follow the ID value)?

SELECT  a.ID
      , a.Title
      , a.Dt
FROM    Table a
        JOIN ( SELECT   b.Title
                      , Dt = MAX(Dt)
               FROM     Table b
               GROUP BY Title
             ) c ON a.Dt = c.Dt
                    AND a.Title = c.Title
Sign up to request clarification or add additional context in comments.

Comments

2
select max(ID) as ID, max(Date), Title
from table
group by Title

should do the trick

2 Comments

This is valid for the data sample but breaks when the max date isn't on the row with the max id
but its not always true that the largest id have the largest date.... i will edit the table...
0
select
max(ID), Title , max(Date)
from
table
group by
Title

3 Comments

This won't work; you're grouping by the ID and the Title, which means all rows will be returned (assuming that the ID is unique).
grouping by the ID which is unique will result in returning all rows
Still not quite there :) You have to do something with the ID column now. Either GROUP with it, or use it in an aggregate.

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.