我有一个表A,它有一个BMI列,我想知道它们中有多少是在这个范围内,我有4个范围。
我想得到类似的结果,我该怎么做sql查询?
<18.5 ,10
18.5–24.9 ,25
25–29.9 ,19
>30 ,2
答案 0 :(得分:2)
select case
when bmi < 18.5 then
'<18.5'
when bmi > 18.5 and < 24.9 then
'18.5–24.9'
when bmi < 25 and > 29.9 then
'25–29.9'
when bmi > 30 then
'>30'
end as bmi_rg,
count(*) as num_bmis
from your_table
group by case
when bmi < 18.5 then
'<18.5'
when bmi > 18.5 and < 24.9 then
'18.5–24.9'
when bmi < 25 and > 29.9 then
'25–29.9'
when bmi > 30 then
'>30'
end
使用CASE语句。要显示每个组的计数,您还必须使用GROUP BY该case语句。
答案 1 :(得分:0)
您可以为每个指定范围创建联合查询
select count(*) from table where bmi < 18.5
union select count(*) from table where bmi >= 18.5 and bmi < 25
union select count(*) from table where bmi >=25 and bmi < 30
union select count(*) from table where bmi > 30
答案 2 :(得分:0)
试试这个:
select case when bmi < 18.5 then '<18.5'
when bmi betwen 18.5 and 24.9 then '18.5–24.9'
when bmi betwen 25 and 29.9 then '25–29.9'
when bmi > 30 then '>30'
end as bmi_group,
count(*) as grp_count
from your_table
group by case when bmi < 18.5 then '<18.5'
when bmi betwen 18.5 and 24.9 then '18.5–24.9'
when bmi betwen 25 and 29.9 then '25–29.9'
when bmi > 30 then '>30'
end
诀窍在于,当在group by中使用相同的CASE语句时,您可以实现基于&#34; BMI范围的分组&#34;而不是实际的BMI值本身。使用Oracle Analytic functions可以实现同样的效果,也可以查看该选项。