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

huangapple go评论47阅读模式
英文:

I need to calculate the sum correctly for the three calculated columns

问题

I need help with my query, where the total of 3 counted columns in one column as total, here is my current query:

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
英文:

I need help with my query, where the total of 3 counted columns in one column as total, here is my current query:

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

答案1

得分: 1

如果您只需要总数,您可以在行内直接求和:

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

If you only need the total, you can just sum it up inline:

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

答案2

得分: 0

你可以使用子查询来计算特定的计数,然后获取计数的总和,而无需重新扫描整个表格:

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;

演示在此

英文:

You can use a subquery to calculate specific counts, and then get the total of counts without having to rescan the entire table again:

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

huangapple
  • 本文由 发表于 2023年5月20日 21:49:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76295564.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定