2

如果我没有返回任何行并且想要硬编码计数和 sysdate 信息的默认值“0”,我该如何重写这个 oracle 查询?

如果没有数据,我的查询现在会给我这个:

 1* SELECT count(*) as MYCNT, timestamp FROM TESTDATA WHERE timestamp = to_char(sysdate-2, 'yyyymmdd') || '0000' group by timestamp
SQL> /

no rows selected

在这里,我尝试了 NVL,但没有得到预期的输出:

1* select nvl(count(*), 0) as MYCNT, to_char(sysdate-2, 'yyyymmdd') || '0000' from TESTDATA WHERE timestamp = to_char(sysdate-2, 'yyyymmdd') || '0000' group by timestamp
SQL> /

no rows selected

想看到这样的东西:

MYCNT    TIMESTMP
-----    --------
0        201107250000
4

3 回答 3

2

group by 正在阻止这只是默认工作。

select count(*) ,  to_char(sysdate-2, 'yyyymmdd') || '0000' as timestamp 
from dual where 1=0

通过将输出与以下内容进行比较,您可以看到这种情况:

select count(*) ,  to_char(sysdate-2, 'yyyymmdd') || '0000' as timestamp 
from dual where 1=0
group by  to_char(sysdate-2, 'yyyymmdd') || '0000' 

第二个版本返回空白,第一个版本返回 0 和时间戳

于 2011-07-26T19:13:45.787 回答
0

尝试这个:

 SELECT count(*) as MYCNT, timestamp 
FROM TESTDATA 
WHERE timestamp = to_char(sysdate-2, 'yyyymmdd') || '0000' 
GROUP BY timestamp 
UNION
SELECT 0, '201107250000'
  FROM dual
于 2011-07-26T19:21:58.310 回答
0

尝试

SELECT 0, to_char(sysdate-2, 'yyyymmdd') || '0000' FROM DUAL WHERE 0 = 
(SELECT count(*) FROM TESTDATA WHERE timestamp = to_char(sysdate-2, 'yyyymmdd') || '0000')
UNION
SELECT count(*) as MYCNT, timestamp FROM TESTDATA WHERE timestamp = to_char(sysdate-2, 'yyyymmdd') || '0000' group by timestamp

如果存在,则返回真实数据,如果不是默认数据

于 2011-07-26T19:12:34.180 回答