返回两个表的结果集中的最新结果

时间:2018-03-26 06:40:20

标签: sql union aggregate-functions

我有一个查询从两个表中搜索最近的事务。查询工作正常并返回 2结果

    SELECT *
FROM
  (SELECT ROW_NUMBER() over (partition BY lower(tb1.email) order by tb1.reserve_date DESC) AS ranking,
    tb1.id,
    tb1.reserve_date
  FROM TableTester1 tb1
  UNION
  SELECT ROW_NUMBER() over (partition BY lower(tb2.email) order by tb2.reserve_date DESC) AS ranking,
    tb2.id,
    tb2.reserve_date
  FROM TableTester2 tb2
  )
WHERE ranking = 1;

但是根据要求,我仍然需要减少它并获得更新的。因此,查询应该只返回 1结果

我已阅读汇总功能并尝试使用 MAX() GROUP BY 功能,如下所示:

SELECT MAX(reserve_date)
FROM
  (SELECT ROW_NUMBER() over (partition BY lower(tb1.email) order by tb1.reserve_date DESC) AS ranking,
    tb1.id,
    tb1.reserve_date
  FROM TableTester1 tb1
  UNION
  SELECT ROW_NUMBER() over (partition BY lower(tb2.email) order by tb2.reserve_date DESC) AS ranking,
    tb2.id,
    tb2.reserve_date
  FROM TableTester2 tb2
  )
WHERE ranking = 1;

但它只会导致 ORA-00979:不是GROUP BY表达式错误。

有关如何解决此问题的任何建议?

3 个答案:

答案 0 :(得分:1)

为什么不限制前两个:

SELECT id, reserve_date
FROM
(
    SELECT
        ROW_NUMBER() OVER (PARTITION BY LOWER(tb1.email)
            ORDER BY reserve_date DESC) AS rn,
        id,
        reserve_date
    FROM TableTester1
) t
WHERE rn <= 2;

如果你真的是指 rank 对应前两个记录的所有记录,那么你可以用ROW_NUMBERRANK替换DENSE_RANK,具体取决于你要使用哪一个。

答案 1 :(得分:0)

使用它:

 SELECT * FROM
 (SELECT ROW_NUMBER() over (partition BY lower(tb.email) order by tb.reserve_date DESC) AS ranking,
tb1.id,
tb1.reserve_date from 
(select * FROM TableTester1 tb1

UNION

select *  FROM TableTester2 tb2
)tb)B
WHERE ranking = 1;

答案 2 :(得分:0)

row_number()

之后执行union all
SELECT tt.*
FROM (SELECT tt.*, ROW_NUMBER() OVER (ORDER BY reserve_date DESC) as seqnm
      FROM ((SELECT tb1.id, tb1.reserve_date
             FROM TableTester1 tb1
            ) UNION ALL
            (SELECT tb2.id, tb2.reserve_date
             FROM TableTester2 tb2
            )
           ) tt
     ) tt
WHERE seqnum = 1;