我正在使用Oracle,我希望将结果从选择计数转换为"二进制" 0/1值... 0 = 0 ...非零= 1.从我在线阅读的内容中,在MS SQL中,您可以将其转换为" bit"但甲骨文似乎并不支持这一点。
这是我的简单示例查询(真正的查询要复杂得多)。我希望MATCH_EXISTS始终为0或1.这可能吗?
select count(*) as MATCH_EXISTS
from MY_TABLE
where MY_COLUMN is not null;
答案 0 :(得分:6)
这应该是最快的...最多获得一行。
SELECT COUNT(*) AS MATCH_EXISTS
FROM MY_TABLE
WHERE MY_COLUMN IS NOT NULL
AND rownum <= 1;
答案 1 :(得分:1)
如果使用exists
子句,对于大型表来说这应该更快,因为Oracle不需要扫描整个表。只要有一行,就可以停止检索它:
select count(*) as match_exists
from dual
where exists (select *
from my_table
where my_column is not null);
答案 2 :(得分:0)
您可以使用CASE WHEN
:
SELECT CASE WHEN MATCH_EXISTS = 0 THEN 0
ELSE 1
END AS MATCH_EXISTS
FROM (SELECT COUNT(*) AS MATCH_EXISTS
FROM MY_TABLE
WHERE MY_COLUMN IS NOT NULL) AS t;
修改强>
SELECT CASE WHEN COUNT(*) = 0 THEN 0
ELSE 1
END as MATCH_EXISTS
FROM MY_TABLE
WHERE MY_COLUMN IS NOT NULL;
答案 3 :(得分:0)
不要做count()
。为了提高性能,请使用exists
:
select (case when exists (select 1 as MATCH_EXISTS
from MY_TABLE
where MY_COLUMN is not null
)
then 1 else 0
end)
from dual;
这可以明显加快。