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

MySql 码拜 8年前 (2016-02-18) 3439次浏览
如题,本人在网上也找过相关解决方法,很多解答都是这么一句SQL语句:
select Id,AccountId,Mark,max(CreateTime) as Latest from AccountMark as b group by AccountId
使用Max函数。但是在本人查出来的数据中似乎有些不对,如图,反白的那一条数据,Mark字段和CreateTime字段根本不对应啊!
Mysql将数据分组后取出时间最近的数据Mysql将数据分组后取出时间最近的数据
这是怎么回事?使用Max函数后在分组这样靠谱吗?
还有一条语句:select *,COUNT(AccountId) as Num from
(select * from AccountMark order by CreateTime desc) `temp`
group by AccountId order by CreateTime desc
这样查出来的数据是对的
Mysql将数据分组后取出时间最近的数据
但是,本人需要创建视图,Mysql中视图里不允许出现查询子句。求高手些一条SQL语句,能实现既不出现子句,又能查出正确数据。谢谢!
解决方案

5

参考下贴中的多种方法
http://blog.csdn.net/acmain_chm/article/details/4126306
[征集]分组取最大N条记录方法征集,及散分….

35

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 )

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明Mysql将数据分组后取出时间最近的数据
喜欢 (0)
[1034331897@qq.com]
分享 (0)