汇总每个用户的最新记录

时间:2018-08-21 08:30:23

标签: mysql sql count sum

我有一张桌子,如下表

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

我想要每个user_id的最新余额,并将它们全部求和。结果,我将从用户001,002,003中获得最新余额的总和

  • 此表包含大约500万条记录
  • 此表保存每个用户的帐户余额的历史记录。因此,最新日期是该用户的最新帐户余额。

下面是我的查询,但是由于MySQL工作台冻结,我没有得到任何结果。

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)

3 个答案:

答案 0 :(得分:3)

这应该很简单,不需要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)

答案 1 :(得分:2)

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

答案 2 :(得分:0)

选择 h1.user_id,SUM(h1.bal) 从 hist_bal h1,hist_bal h2 哪里 h1.createDate =(选择最大值(h2.createDate) 和h2.user_id = h1.user_id
通过...分组 h1.user_id