如果在 Oracle 中未选择任何行,则在列中返回 0

Kan*_*n K 1 oracle

当我在 Oracle DB 中执行查询时,它返回 0 行。如果没有选择任何行,我需要将列值返回为 0。请查找随附的示例查询。

select NVL(staff,0), NVL(code,0)
       from stafftable
      where staffid= 123
        and code in (112, 251)
        and closedate is not null
        and rownum<2
        order by opendate desc;
Run Code Online (Sandbox Code Playgroud)

如果没有选择行,我需要以下结果:

NVL(staff,0)      NVL(code,0)
0                 0
Run Code Online (Sandbox Code Playgroud)

我尝试过 NVL()、coalsce() 无法获得预期结果。

D-S*_*hih 5

我尝试过 NVL()、coalsce() 无法获得预期结果。

因为它确实没有返回任何结果,所以我们可能会得到空结果

我们可以尝试CTE使用UNION ALL

一个用于您的过滤结果,另一个用于空结果的默认结果

WITH cte AS ( 
      select staff, code
       from stafftable
      where staffid= 123
        and code in (112, 251)
        and closedate is not null
        and rownum<2
)
SELECT staff, code
FROM cte
UNION ALL 
SELECT 0 , 0 
FROM dual
WHERE NOT EXISTS (
   SELECT 1
   FROM cte 
) 
Run Code Online (Sandbox Code Playgroud)