Damien
Damien

Reputation: 95

Sum latest records from each user

I have a table as below

id   user_id      bal      createdDate
1    001          100      2015-02-17 16:45:44
2    001          200      2015-02-18 18:45:44
3    002          300      2015-02-20 16:45:44
4    002          800      2015-02-18 18:45:44
5    001          300      2015-03-01 16:20:44
6    002          500      2015-03-17 16:45:44
7    002          200      2015-03-18 18:45:44
8    003          300      2015-03-10 16:45:44
9    003          80       2015-03-18 18:45:44
10   003          200      2015-03-21 16:20:44

I want the latest balance of each user_id and sum all of them. As a result, i will get sum of combine latest balance from user 001,002,003

Below is my query, but I don't get any result as my MySQL workbench froze.

SELECT (SUM(bal))
FROM hist_bal h1
WHERE h1.createDate = (SELECT MAX(h2.createDate)
FROM hist_bal h2
WHERE h2.user_id = h1.user_id  GROUP BY h2.user_id)

Upvotes: 0

Views: 167

Answers (2)

Csaba Benko
Csaba Benko

Reputation: 1161

This should do it simply, no need for GROUP BY clouse:

SELECT SUM(bal)
FROM hist_bal h1
WHERE h1.createDate = (SELECT MAX(h2.createDate)
FROM hist_bal h2
WHERE h2.user_id = h1.user_id)

Upvotes: 3

akshay
akshay

Reputation: 777

SELECT SUM(h1.bal) AS Bal
FROM hist_bal h1 JOIN (SELECT user_id, MAX(h2.createDate) AS createDate
FROM hist_bal h2 GROUP BY h2.user_id) h2 ON h1.user_id = h2.user_id
AND h1.createDate = h2.createDate

Upvotes: 2

Related Questions