在线求助mysql分组后取最大值

时间:2021-11-01 14:35:13
请各位大大帮忙  现有数据如下
table picture
id   name    accountid   location  createtime
1     a          2         1        2007-12-31
2     b          2         3        2007-11-31
3     c          2         2        2007-12-31
4     d          2         2        2007-10-31
5     e          1         1        2007-12-31
6     f          2         1        2008-12-31


我的SQL select * from picture where accountId=2  group by location order by createTime desc limit 0,10

我希望得到的数据  (得到一个account在不同location的日期最近的数据10条)
id   name    accountid   location  createtime
6     f          2         1        2008-12-31
3     c          2         2        2007-12-31
2     b          2         3        2007-11-31

可是我得到的
id   name    accountid   location  createtime
1     a          2         1        2007-12-31
4     d          2         2        2007-10-31
2     b          2         3        2007-11-31

各位大大帮忙看看我该怎么改

6 个解决方案

#1




select  accountid ,location,max(createtime)
from picture
group by accountid ,location

== 思想重于技巧 ==

#2




select * 
from picture p
where createtime=(select max(createtime) from picture where accountid=p.accountid and location=p.location)


== 思想重于技巧 ==

#3


引用 1 楼 liuyann 的回复:
select  accountid ,location,max(createtime)
from picture
group by accountid ,location== 思想重于技巧 ==


的确得到了最大日期值 可是它返回的id并不是最大日期值的那个id

#4




select * 
from picture p inner join (
select  accountid ,location,max(createtime)
from picture
group by accountid ,location ) t
on p.accountid=t.accountid and p.location=t.location and p.createtime=t.createtime


== 思想重于技巧 ==

#5


引用 4 楼 liuyann 的回复:
SQL codeselect*frompicture pinnerjoin(selectaccountid ,location,max(createtime)frompicturegroupbyaccountid ,location ) tonp.accountid=t.accountidandp.location=t.locationandp.createtime=t.createtime== 思想重于技巧 ==


谢谢liuyann 是正确的  结帖

#6


看下实得分是

#1




select  accountid ,location,max(createtime)
from picture
group by accountid ,location

== 思想重于技巧 ==

#2




select * 
from picture p
where createtime=(select max(createtime) from picture where accountid=p.accountid and location=p.location)


== 思想重于技巧 ==

#3


引用 1 楼 liuyann 的回复:
select  accountid ,location,max(createtime)
from picture
group by accountid ,location== 思想重于技巧 ==


的确得到了最大日期值 可是它返回的id并不是最大日期值的那个id

#4




select * 
from picture p inner join (
select  accountid ,location,max(createtime)
from picture
group by accountid ,location ) t
on p.accountid=t.accountid and p.location=t.location and p.createtime=t.createtime


== 思想重于技巧 ==

#5


引用 4 楼 liuyann 的回复:
SQL codeselect*frompicture pinnerjoin(selectaccountid ,location,max(createtime)frompicturegroupbyaccountid ,location ) tonp.accountid=t.accountidandp.location=t.locationandp.createtime=t.createtime== 思想重于技巧 ==


谢谢liuyann 是正确的  结帖

#6


看下实得分是