postgresql 如何合并统计同一表中数据的查询?

7rtdyuoh  于 2023-06-22  发布在  PostgreSQL
关注(0)|答案(1)|浏览(135)

我有这个疑问

select 'firstname' as attr_name, count(id) as count_id, count(id) - count(firstname) as count_missing, count(firstname) as count_total from person
union
select 'lastname' as attr_name, count(id) as count_id, count(id) - count(lastname) as count_missing, count(lastname) as count_total from person

假设第一个查询运行了大约5秒,第二个查询也运行了5秒,如果我运行整个联合查询,那么它将花费大约10秒。所以它基本上运行单个查询并合并结果。
有没有一种方法可以达到同样的效果,但所需的时间会减少?
我想不出除此之外的任何可能的解决方案。

pu3pd22g

pu3pd22g1#

这应该只在整个表中进行一次扫描:

WITH result AS (
  SELECT
    count(id) AS count_id,
    count(firstname) AS count_firstname,
    count(lastname) AS count_lastname
  FROM person
)
SELECT
  'firstname' AS attr_name,
  count_id,
  count_id - count_firstname AS count_missing,
  count_firstname AS count_total
FROM result
UNION ALL
SELECT
  'lastname' AS attr_name,
  count_id,
  count_id - count_lastname AS count_missing,
  count_lastname AS count_total
FROM result

相关问题