【问题标题】:SQL Query to count entries in the column and get percentageSQL 查询以计算列中的条目并获取百分比
【发布时间】:2021-01-22 10:31:42
【问题描述】:
student have new books
alice yes
bob yes
candace no
dalia no
edd no
frank yes

预期输出 50

基本上我想计算有新书的行和学生的总数,并得到有新书的学生的百分比

【问题讨论】:

  • 为您的预期输出添加示例输入。
  • 正在编辑,对这个平台不太熟悉

标签: sql influxdb influxql


【解决方案1】:

使用条件聚合如下:

select count(case when have_new_book = 'yes' then 1 end) / count(*)
 from your_Table

【讨论】:

    【解决方案2】:

    显示了三种方法:

    create table t(student,have_new_books);
    insert into t values
      ('alice',     'yes'),
      ('bob',       'yes'),
      ('candace',   'no'),
      ('dalia',     'no'),
      ('edd',       'no'),
      ('frank',     'yes');
    
    select sum(case have_new_books when 'yes' then 1 else 0 end)*100 / count(*) yes_percent
      from t;
    
    select have_new_books,count(*)*100/(select count(*) from t) percent
      from t
      group by have_new_books;
    
    select sum(have_new_books='yes')*100/count(*) yes_percent
      from t;
    

    使用 SQLite3 进行测试,但它们应该可以在大多数其他引擎上运行(第三个可能仅在 SQLite3 上)。

    输出:

    ┌─────────────┐
    │ yes_percent │
    ├─────────────┤
    │ 50          │
    └─────────────┘
    ┌────────────────┬─────────┐
    │ have_new_books │ percent │
    ├────────────────┼─────────┤
    │ no             │ 50      │
    │ yes            │ 50      │
    └────────────────┴─────────┘
    ┌─────────────┐
    │ yes_percent │
    ├─────────────┤
    │ 50          │
    └─────────────┘
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2015-06-11
      相关资源
      最近更新 更多