【发布时间】:2011-06-27 12:05:16
【问题描述】:
我对 mysql 的 sql 查询有问题,以获取每个组中的最后一条记录并在一个查询中对某些字段求和。我有一个表:
name date interested made_call
andrew.h 2011-02-04 10 10
andrew.h 2011-02-11 20 10
andrew.h 2011-02-13 2 10
sasha.g 2011-02-11 5 20
sasha.g 2011-02-12 5 1
我需要按名称汇总 made_call 列分组并返回感兴趣的最后一条记录。 这是我想要得到的结果:
name date interested made_call
andrew.h 2011-02-13 2 30
sasha.g 2011-02-12 5 21
我试图用这个查询得到结果
SELECT a.name,a.date,a.interested,sum(made_call) as made_call
FROM `resultboard` a
WHERE a.attendence = 1
AND NOT EXISTS (select 1 from resultboard where name = a.name
and id > a.id and attendence = 1)
GROUP BY name
但结果我得到了
andrew.h 2011-02-13 2 10
sasha.g 2011-02-12 5 1
所以查询没有求和,只返回组中的最后一条记录 帮助)
【问题讨论】:
标签: mysql group-by subquery sum