1

在下面的 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
...
4

2 回答 2

1

您发布的t_Inserts查询t_Updatesschema.table. 由于您不使用子句进行查询schema.tableWHERE因此结果集必须包含尽可能多的行schema.table。如果你想要一行,你可以SELECTdual表中

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;
于 2012-12-06T17:51:30.743 回答
1

@Justin 的答案 (+1) 的替代方案:

SELECT COUNT(*)-COUNT(column) AS t_Inserts, COUNT(column) AS t_Updates
FROM schema.table;
于 2012-12-06T17:57:13.210 回答