我有一张桌子,我必须在其中按姓名和性别计算最大值和(计算最大值)组的数量。
sample input:
name sex age
A F 2
A F 3
A M 4
B F 6
B M 7
B M 7
B F 4
C M 8
C M 8
C M 8
C M 3
C F 1
C F 10
C F 10
Sample Output:
name sex max_age count_max_age
A F 3 1
A M 4 1
B F 6 1
B M 7 2
C F 10 2
C M 8 3
我尝试过
select name,sex,max(age) as max_age , count(max_age) from table_1 group by name ,sex
我遇到错误
Unknown column max_age in fieldlist
请提出以上查询所需的任何修改。
预先感谢
答案 0 :(得分:1)
SELECT count(max_age), name, sex FROM (
SELECT name, sex, max(age) as max_age from table_1 group by name, sex
) as max_age_group group by name, sex
查询不会在同一级别理解别名,但是您可以将其作为子查询。
答案 1 :(得分:0)
使用子查询并按如下所示加入
select
t1.name, t1.sex, max_age, count(max_age) as countofmaxage
from
(select name, sex, max(age) as max_age
from t
group by name, sex) t1
join
t on t1.name = t.name and t1.sex = t.sex and t1.max_age = t.age
group by
t1.name, t1.sex, max_age
输出:
name sex max_age countofmaxage
----------------------------------
A F 3 1
A M 4 1
B F 6 1
B M 7 2
C F 10 2
C M 8 3