我需要通过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
我最后需要总结一下。我该怎么办?
答案 0 :(得分:0)
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
答案 1 :(得分:0)
我做到了,我从@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 :(得分:0)
你的目标不明确。
但在这里我试图获得你期望的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