简体   繁体   English

SQL选择总和计数变量

[英]sql select sum count variable

I need to select tableA, count(id) group by acc_id and SUM(6 - total). 我需要选择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

Expecty Result: 预期结果:

 total: 8

I tried: 我试过了:

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

My output: 我的输出:

total: 4, total: 4

I just need to sum it in the end. 我只需要总结一下。 How can I do it? 我该怎么做?

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

I did it, I got code from @Samuel O'Connor and edit it: 我做到了,我从@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 

Thanks for helping me. 谢谢你帮我

Your goal is not clear. 您的目标尚不清楚。

But here my attempt to get your expected 8 但是在这里我试图获得您期望的8

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM