Mysql将数据分组后取出时间最近的数据

如题,我在网上也找过相关解决方法,很多解答都是这么一句SQL语句:
select Id,AccountId,Mark,max(CreateTime) as Latest from AccountMark as b group by AccountId

使用Max函数。但是在我查出来的数据中似乎有些不对,如图,反白的那一条数据,Mark字段和CreateTime字段根本不对应啊!



这是怎么回事?使用Max函数后在分组这样靠谱吗?

还有一条语句:select *,COUNT(AccountId) as Num from
(select * from AccountMark order by CreateTime desc) `temp`
group by AccountId order by CreateTime desc
这样查出来的数据是对的


但是,我需要创建视图,Mysql中视图里不允许出现查询子句。求大神些一条SQL语句,能实现既不出现子句,又能查出正确数据。谢谢!
...全文
39326 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
yiyiaa111 2016-08-17
  • 打赏
  • 举报
回复 2
下面有两种方法:假设你的表叫t_biz_sign ,'最新列'字段叫create_time ,需要分组的字段叫foreign_id SELECT sign.* FROM t_biz_sign sign WHERE NOT exists(SELECT 1 FROM t_biz_sign WHERE foreign_id = sign.foreign_id AND sign.create_time < create_time) ORDER BY create_time DESC; SELECT * FROM t_biz_sign sign WHERE (SELECT count(*) FROM t_biz_sign AS m WHERE m.foreign_id = sign.foreign_id AND m.create_time >= sign.create_time) < 2;
cao11bao 2015-10-28
  • 打赏
  • 举报
回复
太感谢了,正好解决我的问题
  • 打赏
  • 举报
回复
引用 4 楼 wwwwb 的回复:
select *,(select count(distinct mark) from AccountMark where AccountId= b.AccountId) from AccountMark as b where not exists(select 1 from AccountMark where AccountId= b.AccountId and b.CreateTime<CreateTime )
嗯,这个可以了。谢谢各位热心帮助!
  • 打赏
  • 举报
回复
引用 2 楼 ACMAIN_CHM 的回复:
参考下贴中的多种方法 http://blog.csdn.net/acmain_chm/article/details/4126306 [征集]分组取最大N条记录方法征集,及散分....
谢谢,方法很多,受教了。但是我这里该怎么统计出一个AccountId有多少条数据呢?
wwwwb 2014-12-23
  • 打赏
  • 举报
回复
select *,(select count(distinct mark) from AccountMark where AccountId= b.AccountId) from AccountMark as b where not exists(select 1 from AccountMark where AccountId= b.AccountId and b.CreateTime<CreateTime )
  • 打赏
  • 举报
回复
引用 1 楼 wwwwb 的回复:
select * from AccountMark as b where not exists(select 1 from AccountMark where AccountId= b.AccountId and b.CreateTime<CreateTime )
谢谢这位大神的解答,这样查出来的数据是正确的而且避免了查询子句的问题。但是如果我要在这里面统计出每一个AccountId有多少条Mark(最后一张截图里面的Num)该怎么写呢
ACMAIN_CHM 2014-12-23
  • 打赏
  • 举报
回复
参考下贴中的多种方法 http://blog.csdn.net/acmain_chm/article/details/4126306 [征集]分组取最大N条记录方法征集,及散分....
wwwwb 2014-12-23
  • 打赏
  • 举报
回复
select * from AccountMark as b where not exists(select 1 from AccountMark where AccountId= b.AccountId and b.CreateTime<CreateTime )

56,677

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧