首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >group by或having?

group by或having?
EN

Stack Overflow用户
提问于 2014-08-27 06:16:48
回答 3查看 72关注 0票数 0

我有一个表A,其中有一列BMI,我想找出它们中有多少在范围内,我有4个范围。

我想要得到这样的结果,我如何进行sql查询?

代码语言:javascript
复制
<18.5     ,10
18.5–24.9 ,25
25–29.9   ,19
>30       ,2
EN

回答 3

Stack Overflow用户

发布于 2014-08-27 06:29:49

代码语言:javascript
复制
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语句。要显示每个组的计数,还必须按该case语句分组。

票数 2
EN

Stack Overflow用户

发布于 2014-08-27 06:20:50

您可以为每个指定的范围创建联合查询

代码语言:javascript
复制
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
票数 0
EN

Stack Overflow用户

发布于 2014-08-27 06:30:14

试试这个:

代码语言:javascript
复制
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语句时,您可以基于“BMI范围”而不是实际的BMI值本身来实现分组。使用Oracle Analytic functions也可以实现同样的效果,也可以查看该选项。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25516048

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档