使用左连接从两个表中选择最小值

时间:2011-11-18 16:44:13

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

我需要在两个表中选择一组日期的最小值,而我的SQL非常生疏,我想不到......

我有一个包含一些业务对象的表:

create table FOO (
  FOO_ID number(19, 0) not null,
  BAR varchar2(255),
  primary key (FOO_ID)
);

此业务对象的日期为零或多个:

create table A_DATES (
  FOO_ID number(19, 0) not null,
  A_DATE date not null,
  primary key (FOO_ID , A_DATE)
);

同一业务对象还有另一组零或多日期:

create table B_DATES (
  FOO_ID number(19, 0) not null,
  B_DATE date not null,
  primary key (FOO_ID , B_DATE)
);

FOO表包含:

+------+--------+
|FOO_ID|A_STRING|
+------+--------+
|1     |aaa     |
|2     |bbb     |
|3     |ccc     |
+------+--------+

A_DATES表包含:

+------+-----------+
|FOO_ID|A_DATE     |
+------+-----------+
|1     |01-Jan-2001|
|1     |01-Jan-2002|
|2     |01-Jan-2003|
|2     |01-Jan-2004|
+------+-----------+

B_DATES表包含:

+------+-----------+
|FOO_ID|B_DATE     |
+------+-----------+
|1     |01-Jan-2003|
|1     |01-Jan-2004|
|2     |01-Jan-2001|
|2     |01-Jan-2002|
+------+-----------+

我必须编写一个select(所以没有临时表等),为每个FOO选择最小的任一组日期(如果有的话)。结果集应如下所示:

+------+--------+-----------+
|FOO_ID|A_STRING|MY_DATE    |
+------+--------+-----------+
|1     |aaa     |01-Jan-2001|
|2     |bbb     |01-Jan-2001|
|3     |ccc     |<null>     |
+------+--------+-----------+

1 个答案:

答案 0 :(得分:4)

select f.FOO_ID, f.A_STRING, min(d.dt) as 'MY_DATE'
from FOO f
left join (
  select FOO_ID, min(A_DATE) as dt from A_DATES group by FOO_ID
  union select FOO_ID, min(B_DATE) as dt from B_DATES group by FOO_ID
) d
  on f.FOO_ID = d.FOO_ID
group by
  f.FOO_ID, f.A_STRING