Question

Can someone give me a select statement that would retrieve only the rows with the highest (max) YEAR for each user?

Year    User_ID   Name     City
=====   =======   =====    =====
2001    1         Bob      Mpls
2002    1         Bob      Mpls
2003    1         Bob      St Paul
2005    2         Mary     New York
2010    2         Mary     L.A.

...so the result set I would want is:

Year    User_ID   Name   City
=====   =======   ====   =====
2003    1         Bob    St Paul
2010    2         Mary   L.A.
Was it helpful?

Solution

Since you did not mention any RDBMS, this query will work on almost all RDBMS.

SELECT  a.*
FROM    TableName a
        INNER JOIN
        (
            SELECT  Name, MAX(Year) Year
            FROM    TableName 
            GROUP   BY Name
        ) b ON  a.Name = b.Name
                AND a.Year = b.Year

However, if your RDBMS supports window functions, you can use ROW_NUMBER()

SELECT  Year, User_ID, Name
FROM    
        (
            SELECT  Year, User_ID, Name,
                    ROW_NUMBER() OVER (PARTITION BY Name,
                                        ORDER BY Year DESC) rn
            FROM    TableName
        ) x
WHERE   x.rn = 1

OTHER TIPS

SELECT * 
  FROM Table a
  WHERE a.Year = (
                    SELECT TOP 1 Year 
                       FROM Table b 
                       WHERE a.name = b.name 
                       ORDER BY year DESC
                  )

not the best i know but simple

This should work:

SELECT MAX( Year ) Year, User_id, Name
FROM tableName
GROUP BY User_id, Name

If you tell us the database you're using, I may recommend a slightly better query, but this one is simple and should work in most databases:

SELECT MAX(year), user_id, name
FROM myTable
GROUP BY user_id, name

You can acheive the result by group by ,see sample example below ..

    create table #temp(year int,id int,name varchar(5),city varchar(20))
insert into #temp values (2001,1,'Bob','Mpls')
insert into  #temp values (2002,1,'Bob','Mpls')
insert into  #temp values  (2003,1,'Bob','St Paul')
insert into  #temp values  (2005,2,'Mary','New York')
insert into  #temp values  (2010,2,'Mary','L.A.')

you can select like using this query

 SELECT  t.year,t.id,t.Name,t.city
FROM    #temp t
        INNER JOIN
        (
            SELECT  Name, MAX(Year) Year
            FROM    #temp 
            GROUP   BY Name
        ) a ON  t.Name = a.Name
                AND t.Year = a.Year
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top