oracle 使用count(1)计算子查询的记录数

imzjd6km  于 2023-11-17  发布在  Oracle
关注(0)|答案(1)|浏览(190)

我有下面的查询,以验证如果总记录=5。

SELECT COUNT(1)
FROM (
  SELECT COUNT(*) AS total_records
  FROM tbl1
  WHERE version_key = '100047'
 UNION ALL
 SELECT COUNT(*) AS total_records
 FROM tbl2
 WHERE version_key = '100047'
) HAVING COUNT (*)=5;

字符串
这两个子查询的count分别为2和3,但是最终的count不会返回5。如果没有HAVING COUNT (*)=5,最终的count实际上返回2,这是最后一个子查询的计数。

db2dz4w8

db2dz4w81#

子查询将返回每行中每个表的计数。当将其用作引用表时,count(*)将仅返回子查询生成的行数,(在您的情况下始终为2,因为您有两个来自子查询的引用行)。您可以使用sum()函数将每列中的结果相加。您可以尝试使用下面的查询,看看这是否是您所期望的结果吗?

  • MYSQL版本-
SELECT sum(total_records) as final_count
FROM (
  SELECT COUNT(*) AS total_records
  FROM tbl1
  WHERE version_key = '100047'
 UNION ALL
 SELECT COUNT(*) AS total_records
 FROM tbl2
 WHERE version_key = '100047'
) as final_table having final_count = 5;

字符串

  • 编辑2 -
    添加Oracle数据库查询
SELECT sum(total_records) as final_count
FROM (
  SELECT COUNT(*) AS total_records
  FROM tbl1
  WHERE version_key = '100047'
 UNION ALL
 SELECT COUNT(*) AS total_records
 FROM tbl2
 WHERE version_key = '100047'
) having sum(total_records) = 5;


希望这有帮助

相关问题