如何选择最近的日期项目

时间:2017-08-24 13:05:55

标签: sql oracle greatest-n-per-group

我有一张表USER:

select t.* from user t;
uid  uname
1    tom
2    jim
3    bob
4    lily

和表TOYS

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数据库);

2 个答案:

答案 0 :(得分:0)

每个玩具和用户最近的tdate:

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 a.uid, b.tid, a.uname, MAX(b.tdate) 
FROM user a LEFT JOIN toys b ON a.uid = b.uid 
GROUP BY a.uid, a.uname

答案 1 :(得分:0)

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

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