SQL Union返回最近的条目

时间:2013-07-01 09:13:21

标签: sql union

我有两张桌子

TableInitial

EnId  DateSeen
1     2013-05-01
4     2013-05-06
7     2013-05-01
13    2013-05-09
17    2013-05-09

TableFollowup

EnId  FId     DateSeen
1      1      2013-05-04
1      2      2013-05-05
1      3      2013-05-06
4      1      2013-05-09
4      2      2013-05-010
7      1      2013-05-02
13     1      2013-05-011
13     2      2013-05-014
13     3      2013-05-016
13     4      2013-05-019

我想为上面两个表编写一个联合,以便将最近的条目放在一个特定的'EnId'中,如下所示。

结果表我希望如下所示

EnId   FId      DateSeen
1       3       2013-05-06
4       2       2013-05-010
7       1       2013-05-02
13      4       2013-05-019
17    <null>    2013-05-09

我的sql代码是

select EnId, FId, DateSeen  from tableFollowup
WHERE DateSeen =(Select MAX(DateSeen) FROM TableFollowup)

UNION
select EnId, '' AS FId, DateSeen  from tableInitial
GROUP BY EnId

但我似乎得到的是最新的TableInitial和最新的TableFollowup

EnId   FId      DateSeen
1    <null>     2013-05-01
1       3       2013-05-06
4    <null>     2013-05-06
4       2       2013-05-010
7    <null>     2013-05-01
7       1       2013-05-02
7       1       2013-05-02
13    <null>    2013-05-09
13      4       2013-05-019
17    <null>    2013-05-09

我认为我错过了一些东西,但却无法让它发挥作用。 感谢

3 个答案:

答案 0 :(得分:0)

调整您的查询:

select EnId, FId, DateSeen  from tableFollowup t1
WHERE DateSeen =(Select MAX(t2.DateSeen) FROM tableFollowup t2 WHERE t2.EnId = t1.EnId)
UNION
select EnId, '' AS FId, DateSeen  from tableInitial
Where EnId not in (Select enid from tableFollowup)
GROUP BY EnId

答案 1 :(得分:0)

如果Fid总是递增,你可以使用这样的解决方案:

SELECT EnID, MAX(FId), MAX(DateSeen)
FROM (
  SELECT EnID, Null AS FId, DateSeen
  FROM TableInitial
  UNION ALL
  SELECT EnId, FId, DateSeen
  FROM TableFollowup
) s
GROUP BY EnID

请参阅小提琴here。或者您也可以将其用作子查询:

  SELECT EnID, Null AS FId, DateSeen
  FROM TableInitial
  UNION ALL
  SELECT EnId, MAX(FId), MAX(DateSeen)
  FROM TableFollowup
  GROUP BY EnID

(可能会更快)

答案 2 :(得分:0)

这可以根据您的要求为您提供准确的结果。 它也将消除任何复制品。

SELECT MAX(DateSeen), MAX(FId), EnId FROM (select EnId, FId, DateSeen  from tableFollowup
UNION
select EnId, NULL AS FId, DateSeen from tableInitial) dt GROUP BY EnId