急!急!急!急!在两个表中查最大值的SQL怎么写呀?

zpwly 2002-10-31 05:06:33
两个表:table1、 table2
要查: id号和最大日期
条件: 第一种情况:只在其中一个表中有的id号和其对应的最大日期
第二种情况:两个表都有的id号,哪个表的日期大,就取哪个日期
...全文
164 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
xiapb 2002-10-31
  • 打赏
  • 举报
回复
注意:
pandc2002(pc)的思路不错哦,但是需要添加 group by id
zhaoyongzhu(zhaoyongzhu)写法中的 case when 在其他情况下会很有用的
zpwly 2002-10-31
  • 打赏
  • 举报
回复
好了,我是得差不多了,可以结帖了!谢谢各位了!
zpwly 2002-10-31
  • 打赏
  • 举报
回复
chooser(chooser) :

thinks
zpwly 2002-10-31
  • 打赏
  • 举报
回复
我只是想两个比较一下,看哪个更好!没别的意识!
chooser 2002-10-31
  • 打赏
  • 举报
回复
select max(dd),id from (select date dd,id from table1 union all select date dd,id from table2)
这是我的方案,其中ALL去掉也可以,不过效率会底点,旁边没环境,没测过。
chooser 2002-10-31
  • 打赏
  • 举报
回复
pandc2002 写得不是很好吗?你干嘛用别人的?
zpwly 2002-10-31
  • 打赏
  • 举报
回复
zhaoyongzhu(zhaoyongzhu)
你是用两句来实现的,我想用一句,因为查出的条件还要嵌套到其他语句中
zpwly 2002-10-31
  • 打赏
  • 举报
回复
谢谢两位!我正在试验!!
zhaoyongzhu 2002-10-31
  • 打赏
  • 举报
回复
1、select case when max(adate)>max(bdate) then max(aid) else max(bid) end from (select a.date adate,a.id aid,b.date bdate,b.id bid from test1 a,test3 b where a.id<>b.id)
2、select case when max(adate)>max(bdate) then max(aid) else max(bid) end from (select a.date adate,a.id aid,b.date bdate,b.id bid from test1 a,test3 b where a.id=b.id)
pandc2002 2002-10-31
  • 打赏
  • 举报
回复
select max(maxvalue),id from
(
select max(date) maxvalue,id from table1
union all
select max(date) maxvalue,id from table2) as aa

no tested !

17,137

社区成员

发帖
与我相关
我的任务
社区描述
Oracle开发相关技术讨论
社区管理员
  • 开发
  • Lucifer三思而后行
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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