SELECT值,其中日期是子查询中最早的

时间:2016-02-18 12:19:35

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

我想从日期最早的子查询中返回一个值。

表A

id  sub  bid
1   1    1
1   2    2
1   3    1
1   4    1
2   1    2
2   2    1

表B

id value  date
1  red    01/01/2016
1  blue   05/01/2016
2  red    07/01/2016
2  green  03/01/2016
2  yellow 08/01/2016

预期产出

id  sub  value
1   1    red
1   2    green
1   3    red
1   4    red
2   1    green
2   2    red

当前代码

SELECT a.id, 
       a.sub,
       (SELECT b.value FROM tableb b WHERE b.date = MIN(b.date)) AS value
FROM tablea a
INNER JOIN tableb b ON a.bid = b.id

2 个答案:

答案 0 :(得分:2)

假设您希望每id的最低费用:

SELECT a.id, a.sub, b.value
FROM tablea a INNER JOIN
     (SELECT b.*, ROW_NUMBER() OVER (PARTITION BY id ORDER BY date) as seqnum
      FROM tableb b
     ) b
     ON a.bid = b.id and b.seqnum = 1;

答案 1 :(得分:1)

尝试使用NOT EXISTS():

SELECT t.id,t.sub,s.value
FROM TableA t INNER JOIN TableB s ON(t.bid = s.id)
WHERE NOT EXISTS(SELECT 1 FROM tableB f
                 WHERE f.id = s.id and f.date < s.date)

这基本上是连接,然后过滤所有具有更大日期的人,然后过滤当前值以保证所有最新日期。