繁体   English   中英

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

[英]SQL getting max date from two tables

我有两张桌子

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

救命?

您需要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 - 最多两个值。

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

像这样的东西

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

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

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

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

SELECT MAX(updatedDate)as latestUpdated FROM(SELECT updatedDate FROM audio UNION ALL SELECT updatedDate FROM videos)foo

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM