sql select from multiple records only the most recent sql select from multiple records only the most recent sql-server sql-server

sql select from multiple records only the most recent


Try using a subselect to find the lowest ID for each name, and use that set of IDs to pull the records from the main table:

SELECT ID, Name, ValueFROM customer_ageWHERE ID IN(    SELECT MIN(ID) AS ID    FROM customer_age    GROUP BY Name)


Just select the first record for each name using cross apply:

SELECT ca.ID, ca.NAME, ca.VALUEFROM customer_age cCROSS APPLY (SELECT TOP 1 ID, NAME, VALUE        FROM customer_age ca        WHERE ca.NAME = c.NAME ORDER BY ID) caORDER BY ca.ID


How about using window functions??

SELECT Id, Name, ValueFROM (    SELECT Id, Name, Value, ROW_NUMBER() OVER (PARTITION BY Name ORDER BY Id ASC) AS rowNum    FROM customer_age) AS subWHERE rowNum = 1