我有一个如下的MySQL表。
ad_code
然后我需要得到以下结果。
emp_no emp_name dob gender
1 A 1978-10-10 Male
2 B 1985-02-20 Female
3 C 1982-04-16 Female
4 D 1980-06-27 Male
我使用以下查询获取此输出。
age_group No of Male No of Female Total
<25 1 0 1
25-35 0 1 1
35-50 0 1 1
>50 1 0 1
但是我无法得到想要的输出。有人可以帮我解决这个问题吗?
答案 0 :(得分:0)
尝试
SELECT Case
when TIMESTAMPDIFF(YEAR, dob, NOW()) < 25 then '<25'
when TIMESTAMPDIFF(YEAR, dob, NOW()) between 25 and 35 then '25-35'
when TIMESTAMPDIFF(YEAR, dob, NOW()) between 36 and 50 then '36-50'
else '>50' END AS age_group,
sum(if(gender='Male', 1, 0)) as Male,
sum(if(gender='Female', 1, 0)) as Female,
COUNT(1) as total FROM emp
GROUP BY Case
when TIMESTAMPDIFF(YEAR, dob, NOW()) < 25 then '<25'
when TIMESTAMPDIFF(YEAR, dob, NOW()) between 25 and 35 then '25-35'
when TIMESTAMPDIFF(YEAR, dob, NOW()) between 36 and 50 then '36-50'
else '>50' END;
答案 1 :(得分:0)
用例when和子查询
select
case when age_group < 25 then '<25',
case when age_group >= 25 and age_group < 35 then '25-35',
case when age_group >= 35 and age_group < 50 then '35-50',
case when age_group >= 50 then '>=50' else null end as age_grp,
sum(case when gender='Male' then 1 end) as Male,
sum(case when gender='Female' then 1 end) as Female,
sum(case when gender in ('Male','Female') then 1 else 0 end)
as total from
(
SELECT TIMESTAMPDIFF(YEAR, dob, NOW()) AS age_group,gender
FROM emp
) as t group by age_grp
答案 2 :(得分:0)
尝试以下方法:
SELECT Case
when TIMESTAMPDIFF(YEAR, dob, NOW()) < 25 then '<25'
when TIMESTAMPDIFF(YEAR, dob, NOW()) between 25 and 35 then '25-35'
when TIMESTAMPDIFF(YEAR, dob, NOW()) between 36 and 50 then '36-50'
else '>50' END AS age_group,
sum(case when gender='Male' then 1 end) as Male,
sum(case when gender='Female' then 1 end) as Female,
sum(case when gender in ('Male','Female') then 1 end) as total,
GROUP BY Case
when TIMESTAMPDIFF(YEAR, dob, NOW()) < 25 then '<25'
when TIMESTAMPDIFF(YEAR, dob, NOW()) between 25 and 35 then '25-35'
when TIMESTAMPDIFF(YEAR, dob, NOW()) between 36 and 50 then '36-50'
else '>50' END
答案 3 :(得分:0)
您可以尝试以下方法:
select emp_no,
emp_name,
dob,
gender,
case when age < 25 then 1 else 0 end `<25`,
case when age >= 25 and age < 35 then 1 else 0 end `25-35`,
case when age >= 35 and age < 50 then 1 else 0 end `35-50`,
case when age >= 50 then 1 else 0 end `>=50`
from (
select emp_no,
emp_name,
dob,
gender,
year(now()) - year(dob) - (date_format(now(), '%m%d') < date_format(dob, '%m%d'))
age
from tbl
) a