SQL请教

joydraft 2009-05-25 04:37:37
有表如下, ID和Index是主键:
*Id char,
*Index int,
Time TIME,
Info char

请问我怎么能用一条SQL语句选出表中
1)小于当前时间
2)每个ID只选择最大的一个Index的记录

假设有数据如下,
Id, Index, Time, Info
1,1,T,123
1,2,T,234
2,1,T,1234
2,3,T,2345

我用如下SQL不能选出第二行和第四行的Info列。
Select Id, max(Index) From TABLE Group By Id Having Time<now()

还请大家指教,先行多谢了。
...全文
43 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
joydraft 2009-05-25
  • 打赏
  • 举报
回复
非常感谢二位啊
joydraft 2009-05-25
  • 打赏
  • 举报
回复
非常感谢,一点小小的修改就可以了
select a.*
from TABLE1 a,(
select id,max(Index) as mIndex
from TABLE1
where Time <now() Group By id) b
where a.id=b.id and a.Index=b.mIndex
ACMAIN_CHM 2009-05-25
  • 打赏
  • 举报
回复


的确如楼上所说,少了个group by id.

brownman 2009-05-25
  • 打赏
  • 举报
回复
一楼的应该还差点东西吧。出不来结果啊。。。呵呵呵
试试下面的,改了一下一楼的。。。。

select a.* from TABLE1 a,
(select id, max(index1) as mIndex from TABLE1
where time1 < now() group by (id)) b
where a.id = b.id and a.index1 = b.mIndex;
ACMAIN_CHM 2009-05-25
  • 打赏
  • 举报
回复

select a.* 
from TABLE1 a,(
select id,max(Index) as mIndex
from TABLE1
where Time <now()) b
where a.id=b.id and a.Index=b.mIndex


当您的问题得到解答后请及时结贴.
http://topic.csdn.net/u/20090501/15/7548d251-aec2-4975-a9bf-ca09a5551ba5.html

57,062

社区成员

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

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