Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/oracle/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何选择最近日期项目_Sql_Oracle_Greatest N Per Group - Fatal编程技术网

Sql 如何选择最近日期项目

Sql 如何选择最近日期项目,sql,oracle,greatest-n-per-group,Sql,Oracle,Greatest N Per Group,我有一个表用户: select t.* from user t; uid uname 1 tom 2 jim 3 bob 4 lily 和桌上玩具 select t.* from toys t; tid uid tdate 1 1 7/12/15 2 1 6/12/15 3 2 9/12/15 4 2 10/12/15 5 3 12/12/15 现在我想要 uid tid uname tdate

我有一个表用户:

select t.* from user t;
uid  uname
1    tom
2    jim
3    bob
4    lily
和桌上玩具

select t.* from toys t;
tid  uid  tdate
1    1    7/12/15
2    1    6/12/15
3    2    9/12/15
4    2    10/12/15
5    3    12/12/15
现在我想要

uid  tid   uname  tdate
1    2     tom    6/12/15
2    3     jim    9/12/15
3    5     bob    12/12/15
4          lily

我该怎么办?(我使用oracle数据库)

每个玩具和用户的最新日期:

SELECT a.uid, b.tid, a.uname, MAX(b.tdate) AS tdate
FROM user a LEFT JOIN toys b ON a.uid = b.uid 
GROUP BY a.uid, b.tid, a.uname
或每个用户最近的玩具(如有):


您可以为每个用户生成一个序列,并仅返回每个玩具的最小日期:

SELECT user.uid, toys.tid, user.name, toys.tdate 
  FROM    
      (SELECT tid, uid, tdate, 
      ROW_NUMBER() OVER (PARTITION BY uid ORDER BY tdate asc)
      AS SEQ
      FROM toys
     )table1
LEFT JOIN user on toys.uid = user.uid
WHERE SEQ = 1

您希望玩具的用户按日期排序,还是只希望玩具的用户按最新日期排序?使用最短日期,您认为是正确的,但写入错误。此sql无法执行
SELECT user.uid, toys.tid, user.name, toys.tdate 
  FROM    
      (SELECT tid, uid, tdate, 
      ROW_NUMBER() OVER (PARTITION BY uid ORDER BY tdate asc)
      AS SEQ
      FROM toys
     )table1
LEFT JOIN user on toys.uid = user.uid
WHERE SEQ = 1