在下面的SQL语句中,为什么它返回具有正确计数而不是一行的多行?
SELECT
(
SELECT COUNT(*) FROM schema.table t WHERE t.column IS NULL
) AS t_Inserts,
(
SELECT COUNT(*) FROM schema.table t WHERE t.column IS NOT NULL
) AS t_Updates
FROM
schema.table t;
注意:我正在使用Oracle。
Output:
t_Inserts,t_Updates
100,200
100,200
100,200
100,200
100,200
...
答案 0 :(得分:1)
您发布的查询会为t_Inserts
中的每一行运行t_Updates
子查询(以及schema.table
子查询)一次。由于您查询的schema.table
没有WHERE
子句,因此结果集必须包含与schema.table
一样多的行。如果您想要一行,可以从SELECT
表
dual
SELECT
(
SELECT COUNT(*) FROM schema.table t WHERE t.column IS NULL
) AS t_Inserts,
(
SELECT COUNT(*) FROM schema.table t WHERE t.column IS NOT NULL
) AS t_Updates
FROM
dual
但是,做一些像
这样的事情可能会更有效率SELECT SUM( CASE WHEN t.column IS NULL THEN 1 ELSE 0 END ) t_inserts,
SUM( CASE WHEN t.column IS NOT NULL THEN 1 ELSE 0 END ) t_updates
FROM schema.table t;
答案 1 :(得分:1)
@ Justin回答的替代方案(+1):
SELECT COUNT(*)-COUNT(column) AS t_Inserts, COUNT(column) AS t_Updates
FROM schema.table;