如果我没有返回任何行并且想要为计数和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
答案 0 :(得分:2)
该小组正在阻止这种行为的侮辱。
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并且时间戳
答案 1 :(得分: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
这将返回真实数据(如果存在),如果不存在则返回
答案 2 :(得分: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