【问题标题】:sql select sum count variablesql选择总和计数变量
【发布时间】:2017-01-05 16:24:58
【问题描述】:

我需要通过 acc_id 和 SUM(6 - total) 选择 tableA、count(id) 组。

TableA
ID | acc_id | user_id
1  |  2     |   20
2  |  2     |   21
3  |  3     |   22
4  |  3     |   10

预期结果:

 total: 8

我试过了:

select 6-count(id) as total
from tableA 
group by acc_id 
having total < 6 AND total <> 0

我的输出:

total: 4, total: 4

我只需要最后总结一下。我该怎么做?

【问题讨论】:

  • checkout rollup mysql 中的函数以及group by
  • 什么是6-count(id)
  • @RiggsFolly:我认为他计算了 id 的数量,然后计算出 6 减去该数字。所以6 - COUNT(id)
  • @WillemVanOnsem 哦,是的... DUH 傻我
  • 是的,我需要分这个号码

标签: mysql sql


【解决方案1】:

我做到了,我从@Samuel O'Connor 获得了代码并对其进行了编辑:

 select sum(if(total = 0,6,total)) as total_sum
    from(
      select
          6-count(id) as total 
            from tableA 
            group by acc_id) sub
            where total < 6 

谢谢你帮助我。

【讨论】:

    【解决方案2】:

    你的目标不明确。

    但在这里我试图得到你预期的 8

    http://sqlfiddle.com/#!9/a4b76/3

    SELECT SUM(t.total)
    FROM (
    SELECT 6-COUNT(id) as total
    FROM TableA
    GROUP BY acc_id) t
    

    【讨论】:

      【解决方案3】:
      SELECT SUM(total)
      FROM (
          SELECT 6-count(id) AS total
          FROM tableA 
          GROUP BY acc_id
      ) sub
      GROUP BY total
      HAVING total < 6 AND total <> 0
      

      【讨论】:

      • 它没有用,我得到了这个:“有子句”中的未知列“总计”
      • HAVING 子句应该在子查询中。
      • 也可以改成WHERE
      • @Barmars 选项或我编辑的答案都应该有效
      • 它正在工作,但它的总和等于 0,它确实算作加 6
      猜你喜欢
      • 2013-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-05
      • 2014-04-09
      • 2010-10-23
      • 2014-05-13
      相关资源
      最近更新 更多