3

Hello I have the following table design

ID       account_id       score     date
------------------------------------------    
1       500             4               x
2       764             4               x
3       500             6               x
4       500             7               x
5       764             5               x

I'm trying to get all rows with the latest account_id entry

so my code should return

ID       account_id       score     date
------------------------------------------    
4       500             7               x
5       764             5               x

I tried the following code but it seems to return the first entry but with the latest date

SELECT account_id,score, max(date) from table group by account_id
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Amanda1990
  • 77
  • 7

5 Answers5

0

try it-

SELECT distinct a.id,a.account_id,b.score,b.date 
FROM mytable b 
JOIN 
(
SELECT account_id,MAX(id) AS id 
FROM mytable 
GROUP BY account_id
) a ON a.account_id=b.account_id
ORDER BY a.id;
Zafar Malik
  • 6,734
  • 2
  • 19
  • 30
0

Case 1: If id is auto-increment column or max(id) means latest row.

select * from
(select * from table_name
order by id desc) temp
group by account_id 

Case 2: If date column decides latest row then replace id by date in order clause and group clause.

seahawk
  • 1,872
  • 12
  • 18
0

This question is just a duplicate of SQL Select only rows with Max Value on a Column

There you'll find a good explanation.

Community
  • 1
  • 1
0
SELECT a.* 
FROM table a
INNER JOIN (
  SELECT `account_id`,MAX(`date`) AS latest FROM table GROUP BY account_id 
) b
ON a.`date` = b.`latest` AND a.`account_id` = b.`account_id`
ORDER BY `date` DESC

Reference :

Using ORDER BY and GROUP BY together

Community
  • 1
  • 1
Surabhil Sergy
  • 1,946
  • 1
  • 23
  • 40
0

Try using this query it works fine

Select a.account_id,a.score,a.date
from authors as a
join
(Select account_id,max(date) as date
from authors
group by account_id) as d
on(d.date=a.date)
vineeth
  • 641
  • 4
  • 11
  • 25