postgresql 我需要正确计算三个计算列的总和

55ooxyrt  于 2023-05-22  发布在  PostgreSQL
关注(0)|答案(2)|浏览(293)

我需要帮助我的查询,其中一列中的3个计数列的total为total,以下是我当前的查询:

SELECT region, COUNT(s_code), COUNT(b_code), COUNT(d_code), SUM(COUNT(s_code, b_code, d_code)) as total
FROM shilpy
GROUP BY region 
ORDER BY region
smdncfj3

smdncfj31#

如果你只需要总数,你可以直接把它加起来:

SELECT region, 
       COUNT(s_code) + COUNT(b_code) + COUNT(d_code) AS total
FROM shilpy
GROUP BY region 
ORDER BY region
y1aodyip

y1aodyip2#

您可以使用子查询来计算特定的计数,然后获得计数的总数,而无需再次重新扫描整个表:

select *, (count_s + count_b + count_d) as total
from (
  select region, count(s_code) as count_s, count(b_code) as count_b, count(d_code) as count_d
  from shilpy
  group by region 
  order by region
) as s;

Demo here

相关问题