SQL从两个表中获取最大日期

时间:2009-11-24 12:58:41

标签: sql oracle max

我有两张桌子

USER (one row per user)

id,username,firstname,lastname,lastmodified
1,johns, John,Smith, 2009-03-01
2,andrews, Andrew,Stiller, 2009-03-03


STUDIES (multiple rows per user)

id,username,lastmodified
1,johns, 2009-01-01
1,johns, 2009-02-01
1,johns, 2009-07-01
2,andrews,2009-05-05
2,andrews,2009-04-04

我想从两个表中获取用户详细信息和最新日期:

johns,John,Smith,2009-07-01
andrews,Andrew,Stiller,2009-05-05

帮助?

5 个答案:

答案 0 :(得分:10)

这里需要MAX和GREATEST功能的组合:

select u.username
     , u.firstname
     , u.lastname
     , greatest(u.lastmodified,max(s.lastmodified))
  from USER u
     , STUDIES s
 where s.id = u.id
 group by u.id
     , u.username
     , u.firstname
     , u.lastname
     , u.lastmodified

MAX - 用于聚合,GREATEST - 最多两个值。

答案 1 :(得分:0)

SELECT MAX(Date) FROM Users u FULL JOIN Studies s ON u.Username=s.Username GROUP BY Username

答案 2 :(得分:0)

像这样的东西

select username, max(lastmodified) from (
   select username, lastmodified from user 

   union all

   select username, max(lastmodified) as lastmodified 
   from studies
   group by username
) s
group by username

答案 3 :(得分:0)

对于那些需要简单直接选择的人:

select max(lastmodified) 
from (
    select max(lastmodified) as lastmodified from USER 
    union 
    select max(lastmodified) as lastmodified from STUDIES
);

这将获得USER的最大日期,然后是来自STUDIES的最大日期,然后它将返回那些2的最大值。此外,您可能希望在内部选择中添加where子句和一些条件以改善结果

答案 4 :(得分:0)

选择    MAX(updatedDate)为latestUpdated 从     (         SELECT updatedDate FROM audio         UNION ALL         SELECT updatedDate FROM videos     )FOO