【问题标题】:SQL using more two columns with caseSQL 使用更多带有大小写的两列
【发布时间】:2019-03-11 18:28:13
【问题描述】:

我找不到一个很好的解释我的问题。

我有一张桌子:

user   | 70Y   | hospital
-------+-------+----------
1      | 18    | 1   
2      | 70    | 1 
3      | 90    | 0

我需要找出有多少人有超过 70 岁,如果有的话,其中有多少人在医院。

我正在用这个来查找他的年龄是否超过70:

SUM(CASE WHEN 70y > 70 THEN 1 ELSE 0 END) AS 'old_person'

但是我怎么知道他在医院呢?

我对表格的期望是:

 | old_person | old_person_in_hospital| 
 +------------+-----------------------+
 | 18         |              1        | 

如果我想要更多的列,比如说检查 40 岁,那么最简单的方法是什么?

我对表格的期望:

             | old_person  |  40y_person         | 
             +-------------+---------------------+
             | 18          |            16       | 
in hospital  | 1           |             2       | 

【问题讨论】:

    标签: sql sql-server database datatable


    【解决方案1】:

    每列都需要一个案例:

    select 
      SUM(Case when [70y] > 70 then 1 else 0 end) old_person,
      SUM(Case when [70y] > 70 and hospital = 1 then 1 else 0 end) old_person_in_hospital
    from tablename
    

    【讨论】:

    • 使用 MAX 代替 SUM 可能更好。不想让 old_person_in_hospital 的值为 5
    • @SeanLange 为什么?这些列包含人的年龄,并计算有多少人超过 70 岁。
    • 因为看起来他们希望按用户分组。或者可能不是。很难说 OP 真正想要什么。
    • @SeanLange OP 想要统计有多少用户超过 70 岁,其中有多少人在医院。
    【解决方案2】:

    在医院计数中使用另一个案例

    select SUM(Case when 70y > 70 then 1 else 0 end) as old_person,
      sum (Case when 70y > 70 and hospital=1 then 1 else 0 end ) hospital
    from tbale
    

    【讨论】:

      【解决方案3】:

      将条件移至where 子句怎么样?

      select count(*) as old_person,
             sum(hospital) as old_person_in_hospital
      from tablename
      where [70y] > 70;
      

      如果您想添加更多年龄组,那么您可以使用条件聚合。但是,我可能会建议您改用聚合并将结果放在不同的行中。例如:

      select (age / 10) as decade,
             count(*) as num_people,
             sum(hospital) as num_in_hospital
      from tablename
      group by (age / 10);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-21
        • 1970-01-01
        • 2020-06-20
        相关资源
        最近更新 更多