MySQL为列中的每个唯一项选择计数行
用一个例子来解释是最容易的。假设我有一张有3列的桌子——父亲、他们的后代和他们孩子的性别。结果表将列出父亲的子女数量以及男女比例 这是表格:MySQL为列中的每个唯一项选择计数行,mysql,inner-join,Mysql,Inner Join,用一个例子来解释是最容易的。假设我有一张有3列的桌子——父亲、他们的后代和他们孩子的性别。结果表将列出父亲的子女数量以及男女比例 这是表格: Father Child Sex ----------------------- alpha name1 m alpha name2 f alpha name3 m alpha name4 f alpha name5 f beta name6 m beta name
Father Child Sex
-----------------------
alpha name1 m
alpha name2 f
alpha name3 m
alpha name4 f
alpha name5 f
beta name6 m
beta name7 m
charlie name8 f
charlie name9 m
预期结果:
Father num m f
-----------------------
alpha 5 2 3
beta 2 2 0
charlie 2 1 1
num = number of children
m = male, f = female
当我使用count时,它会给我所有父亲的孩子总数,我不知道如何将结果分为男性和女性。
有什么想法吗?类似这样的想法:
select distinc t.Father,
(select count(1) from table t1 where t1.Father = t.Father) as num,
(select count(1) from table t1 where t1.Father = t.Father and Sex = 'm') as m,
(select count(1) from table t1 where t1.Father = t.Father and Sex = 'f') as f
from table t;
大概是这样的:
select distinc t.Father,
(select count(1) from table t1 where t1.Father = t.Father) as num,
(select count(1) from table t1 where t1.Father = t.Father and Sex = 'm') as m,
(select count(1) from table t1 where t1.Father = t.Father and Sex = 'f') as f
from table t;
诀窍是在布尔变量周围使用
SUM()
SELECT Father, COUNT(Child) as num, SUM(Sex='m') as m, SUM(Sex='f') as f
FROM table
GROUP BY Father;
诀窍是在布尔变量周围使用
SUM()
SELECT Father, COUNT(Child) as num, SUM(Sex='m') as m, SUM(Sex='f') as f
FROM table
GROUP BY Father;
尝试:
尝试:
显示返回错误计数的sql语句显示返回错误计数的sql语句counts@RobertRozas多亏了正确的拼写…但还没有测试。格里耶什和我回到了过去。他是SQL公司的人。我只是为了好玩。@dredness谢谢:)我在想@GrijeshChauhan-哦,是的,伙计!发件人:)德鲁内斯的好人xD@RobertRozas多亏了正确的拼写…但还没有测试。格里耶什和我回到了过去。他是SQL公司的人。我只是为了好玩。@dredness谢谢:)我在想@GrijeshChauhan-哦,是的,伙计!发件人:)好人@德鲁内斯xD