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

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

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:

  1. SELECT region, COUNT(s_code), COUNT(b_code), COUNT(d_code), SUM(COUNT(s_code, b_code, d_code)) as total
  2. FROM shilpy
  3. GROUP BY region
  4. 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:

  1. SELECT region, COUNT(s_code), COUNT(b_code), COUNT(d_code), SUM(COUNT(s_code, b_code, d_code)) as total
  2. FROM shilpy
  3. GROUP BY region
  4. ORDER BY region

答案1

得分: 1

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

  1. SELECT region,
  2. COUNT(s_code) + COUNT(b_code) + COUNT(d_code) AS total
  3. FROM shilpy
  4. GROUP BY region
  5. ORDER BY region
英文:

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

  1. SELECT region,
  2. COUNT(s_code) + COUNT(b_code) + COUNT(d_code) AS total
  3. FROM shilpy
  4. GROUP BY region
  5. ORDER BY region

答案2

得分: 0

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

  1. select *, (count_s + count_b + count_d) as total
  2. from (
  3. select region, count(s_code) as count_s, count(b_code) as count_b, count(d_code) as count_d
  4. from shilpy
  5. group by region
  6. order by region
  7. ) 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:

  1. select *, (count_s + count_b + count_d) as total
  2. from (
  3. select region, count(s_code) as count_s, count(b_code) as count_b, count(d_code) as count_d
  4. from shilpy
  5. group by region
  6. order by region
  7. ) 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:

确定