Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql select from multiple records only the most recent

Tags:

sql-server

i have a table named customer_age that loks like this:

ID     1   2    3     4     5    6     7     8     9

NAME  JIM  JIM  JIM  NICK  NICK  NICK  Paul  Paul  Paul                                       
VALUE  20  13   12    10    20    8     4     24    14  

and i want to display only the first record from each name. Something like this

ID     1     4      7    

NAME  JIM  NICK   Paul                                  
VALUE  20   10      4    

So far i have not been able to work it out. i use sql server 2005 Any help would be appreciated...

like image 264
user1211398 Avatar asked Feb 15 '12 15:02

user1211398


People also ask

How do I select most recent records in SQL?

In SQL Server, we can easily select the last 10 records from a table by using the “SELECT TOP” statement. The TOP clause in SQL Server is used to control the number or percentage of rows from the result. And to select the records from the last, we have to arrange the rows in descending order.

How do I get the latest record in SQL for each ID?

Retrieving the last record in each group using GROUP BY In both these solutions, we will be using the MAX() function to get the maximum value of id and then retrieving the other columns corresponding to this maximum id.

How do I get last 3 records in SQL?

SELECT * FROM (select * from suppliers ORDER BY supplier_name DESC) suppliers2 WHERE rownum <= 3 ORDER BY rownum DESC; Notice that although you want the last 3 records sorted by supplier_name in ascending order, you actually sort the supplier_name in descending order in this solution.


3 Answers

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, Value
FROM customer_age
WHERE ID IN
(
    SELECT MIN(ID) AS ID
    FROM customer_age
    GROUP BY Name
)
like image 108
Mark Byers Avatar answered Sep 25 '22 02:09

Mark Byers


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

SELECT 
ca.ID, ca.NAME, ca.VALUE
FROM customer_age c
CROSS APPLY (SELECT TOP 1 ID, NAME, VALUE 
       FROM customer_age ca 
       WHERE ca.NAME = c.NAME ORDER BY ID) ca
ORDER BY ca.ID
like image 33
Diego Avatar answered Sep 25 '22 02:09

Diego


How about using window functions??

SELECT Id, Name, Value
FROM (
    SELECT Id, Name, Value, ROW_NUMBER() OVER (PARTITION BY Name ORDER BY Id ASC) AS rowNum
    FROM customer_age
) AS sub
WHERE rowNum = 1
like image 43
Umair Avatar answered Sep 24 '22 02:09

Umair