我想计算学生表中指定特定年份的男,女,全学生数.我希望结果可以显示在表格中:
====================================
| Label | Value | Year |
====================================
| Male | 0 | 2013 |
| Female | 23 | 2013 |
| Total | 23 | 2013 |
====================================
Run Code Online (Sandbox Code Playgroud)
如果指定年份没有男性/女性匹配,则查询应显示0.知道如何才能实现这一目标吗?
提前致谢
nta*_*lbs 13
考虑以下查询:
select
max(registeredYear) as year,
count(case when gender='Male' then 1 end) as male_cnt,
count(case when gender='Female' then 1 end) as female_cnt,
count(*) as total_cnt
from student
where registeredYear = 2013
group by registeredYear;
Run Code Online (Sandbox Code Playgroud)
结果将是这样的:
Year male_cnt female_cnt total_cnt
---- -------- ---------- ---------
2013 0 23 23
Run Code Online (Sandbox Code Playgroud)
您可以将此结果转换为所需的表单.如果你想在查询中这样做,那么你可以这样做:
with t as (
select
max(registeredYear) as year,
count(case when gender='Male' then 1 end) as male_cnt,
count(case when gender='Female' then 1 end) as female_cnt,
count(*) as total_cnt
from student
where registeredYear = 2013
group by registeredYear)
select 'Male', male_cnt as male, year from t
union all
select 'Female', female_cnt as male, year from t
union all
select 'Total', total_cnt as male, year from t
;
Run Code Online (Sandbox Code Playgroud)
小智 5
你应该使用:
select name, COUNT(*)as tot,
COUNT(case when details.gender='male' then 1 end) as male,
COUNT(case when details.gender='female' then 1 end) as female
from details group by name
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
52230 次 |
| 最近记录: |