首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >获取每组中的最后一条记录,并对其中的一些记录求和

获取每组中的最后一条记录,并对其中的一些记录求和
EN

Stack Overflow用户
提问于 2011-02-15 18:16:03
回答 3查看 4.1K关注 0票数 0

我在对mysql的sql查询中遇到了一个问题,即获取每个组中的最后一条记录,并在一个查询中对一些字段求和。我有一个表:

代码语言:javascript
运行
复制
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列分组求和,并返回感兴趣的最后一条记录。下面是我想要得到的结果:

代码语言:javascript
运行
复制
name        date    interested  made_call
andrew.h    2011-02-13      2         30
sasha.g  2011-02-12      5         21

我试着用这个查询得到结果

代码语言:javascript
运行
复制
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

但结果是我得到了

代码语言:javascript
运行
复制
  andrew.h  2011-02-13      2         10
  sasha.g    2011-02-12      5         1

所以查询没有求和,只返回组帮助中的最后一条记录)

EN

Stack Overflow用户

发布于 2011-02-15 18:28:12

如果表非常大,这可能会有点慢,但它会得到想要的结果:

代码语言:javascript
运行
复制
SELECT a.name, t.date, a.interested, t.calls
FROM resultboard a 
JOIN (SELECT name, MAX(date) AS date, SUM(made_call) AS calls FROM resultboard 
     GROUP BY name) AS t
     ON a.name = t.name AND a.date = t.date
票数 0
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5002335

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档