Oracle FETCH FIRST 1 ROW with UNION ALL 语句

Oracle FETCH FIRST 1 ROW with UNION ALL statement

我正在尝试使用 FETCH FIRST 1 ROW 在 SQL 中创建一个 UNION ALL 语句,但是当我这样做时它给我一个错误 MISSING KEYWORD

这是我的 SQL 的样子:

Select * From tabl1 where Date = '04-MAR-2020' FETCH FIRST 1 ROW

UNION ALL

Select * From tabl1 where Date = '05-MAR-2020' FETCH FIRST 1 ROW

这样的事情是可行的。我想将其保留为单个语句,而不是添加 SUBQUERY 或任何类似的内容。

您可以使用 row_number() 代替:

select t.*
from mytable t
where date in (date '2020-03-04', date '2020-03-05')
order by row_number() over(partition by trunc(date) order by date)
fetch first 1 row with ties

row_number() 将每个 day 放在不同的分区中,并按日期升序排列每一天的记录。然后,您可以使用带有 with ties 选项的行限制子句来获取每天的第一条记录。

这比 union all 解决方案更有效,因为它只扫描 table 一次。


如果你想要union all,那么你可以做:

select *
from (
    (select * from tabl1 where date = date '2020-03-04' order by date fetch first 1 row)
    union all
    (select * from tabl1 where date = date '2020-03-05' order by date fetch first 1 row)
)

试试这个

Select * From tabl1 where Date = '04-MAR-2020' and ROWNUM <= 1
UNION ALL
Select * From tabl1 where Date = '05-MAR-2020' and ROWNUM <= 1

只需将每个部分放在括号中即可。在 12.2 中工作,无论如何:

( Select * From tabl1 where Date = '04-MAR-2020' FETCH FIRST 1 ROW )
UNION ALL
( Select * From tabl1 where Date = '05-MAR-2020' FETCH FIRST 1 ROW )

我的实际测试查询,任何感兴趣的人都是这样的:

(select   object_name 
 from     user_objects 
 where    object_type = 'TABLE' 
 order by object_name 
 fetch first 1 row only)
UNION ALL
(select   object_name 
 from     user_objects 
 where    object_type = 'VIEW' 
 order by object_name 
 fetch first 1 row only);