だけ集約を使用してクエリを作成:
select (case when officerage < 19 then 'Under 19'
when officerage < 30 then '19-29'
when officerage < 40 then '30-39'
else 'old!'
end) as officeragegrp,
sum(case when citizenage < 19 then 1 else 0 end) as [Under 19],
sum(case when citizenage >= 19 and citizenage < 30 then 1 else 0 end) as [19-29],
sum(case when citizenage >= 30 and citizenage < 40 then 1 else 0 end) as [30-39],
sum(case when citizenage > 39 then 1 else 0 end) as [Old!]
from t
group by (case when officerage < 19 then 'Under 19'
when officerage < 30 then '19-29'
when officerage < 40 then '30-39'
else 'old!'
end)
order by min(officerage);
はEDIT:
あなたが存在しなくてもグループを含める必要がある場合は、left join
ができます:
select officeragegroupp,
sum(case when citizenage < 19 then 1 else 0 end) as [Under 19],
sum(case when citizenage >= 19 and citizenage < 30 then 1 else 0 end) as [19-29],
sum(case when citizenage >= 30 and citizenage < 40 then 1 else 0 end) as [30-39],
sum(case when citizenage > 39 then 1 else 0 end) as [Old!]
from (select 'Under 19' as officeragegroup union all
select '19-29' union all
select '30-39' union all
select 'old!'
) oag left join
(select t.*,
(case when officerage < 19 then 'Under 19'
when officerage < 30 then '19-29'
when officerage < 40 then '30-39'
else 'old!'
end) as officeragegroup
from t
) t
on t.officeragegroup = oag.officeragegroup
group by oag.officeragegroup
order by min(t.officerage);
ナイス!しかし、0歳以上の[19歳未満]の年齢層は含まれていません。 (値が0より大きい場合はそれを含めることを意味しますが、ええ) –