create table kids(
familyID bigint references a table with families;
personID bigint references something that contains records with people/kids
)
一个家庭可以有多个 child ,即 sibling 。这个想法是计算有多少家庭有 sibling 。
这个查询:
select count(familyID) from kids group by familyID;
将生成一个结果集,显示每个家庭的 child 总数。所以大多数家庭会有 1 个 child ,一些 2 个 child ,等等。
现在的想法是进一步统计有多少个家庭有一个 child ,有多少个 2 个 child ,有多少个 3 个 child ,所以结果集应该是这样的:
kids count(familyID)
1 44
2 10
3 2
4 1
如果您对数据库中的 count(familyID) 求和:44+11+2+1=total_number_of_families。
我正试图通过子查询到达那里,但似乎无法理解这个概念。谁能解释一下?
最佳答案
你可以用一个临时表来做
select kids , count(*) from
(
select familyID, count(*) kids
from kids
group by familyID ) as t
group by kids
关于mysql - sql中记录的两级计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37818946/