-2

I trying to get the last result (balance) of each distinct account on the table (example bellow). I tried using GROUP BY but it returns the first rows finded.

My expected result is him to return me the rows 4 (last balance from account 2) and row 5 (last balance from account 1), instead it return the rows 1 and 3 (first balance from each account)

SQL used:

select * from sample_table group by account_id;

Sample Table:

+-------------+------------+
| id | account_id | balance|
+----+------------+--------+
|  1 |          1 | 100.00 |
|  2 |          1 | 150.00 |
|  3 |          2 |  50.00 |
|  4 |          1 | 130.00 |
|  5 |          2 |  70.00 |
+-------------+------------+
ThiagoYou
  • 308
  • 3
  • 12

1 Answers1

0

You can do it like this:

SELECT t1.*
FROM sample_table t1 LEFT JOIN sample_table t2
 ON (t1.account_id = t2.account_id AND t1.id < t2.id)
WHERE t2.id IS NULL;
Sookie Singh
  • 1,543
  • 11
  • 17