sql - 如何解决postgresql中group by和aggregate函数的问题

标签 sql postgresql select rdbms

我正在尝试编写一个查询来划分这两个 SQL 语句,但它显示了我

 ERROR: column "temp.missed" must appear in the GROUP BY clause or be used in 
 an aggregate function
  SQL state: 42803

虽然当我按 temp.missed 进行分组时,它似乎有效但由于多个分组依据而显示错误的结果。

我在 PostgreSQL 中有以下表格

 create table test.appointments (
      appointment_id serial
      , patient_id integer references test.patients(id)
      , doctor_id integer references test.doctors(id)
      , appointment_time timestamp
      , appointment_status enum('scheduled','completed','missed')
      );

 create table test.visits (
      visit_id serial
      , patient_id integer references test.patients(id)
      , doctor_id integer references test.doctors(id)
      , walk_in_visit boolean
      , arrival_time timestamp
      , seen_time timestamp
      );

我已经编写了以下查询来查找错过的约会率(错过的约会/总约会),但它显示了上述错误。

  select tem.doctor_id, (temp.missed::float/tem.total) as ratio from 
    (select doctor_id, count(appointment_status) as missed from appointments 
     where appointment_status='missed' group by doctor_id)as temp
      join (select doctor_id, count(appointment_status) as total from 
      appointments group by doctor_id) as tem  on temp.doctor_id = 
       tem.doctor_id group by tem.doctor_id;

最佳答案

您不需要所有这些子查询 - 应用于 case 表达式的 count 函数会简单得多:

SELECT   doctor_id, 
         COUNT(CASE appointment_status 
                    WHEN 'missed' THEN 1 
                    ELSE NULL 
               END)::float / 
         COUNT(*) AS ratio
FROM     appointments
GROUP BY doctor_id

关于sql - 如何解决postgresql中group by和aggregate函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30431574/

相关文章:

mysql - sql 选择移动范围

postgresql - 如何手动锁定和解锁一行?

mysql - 获得最高分和胜利次数

postgresql - Postgresql 中缺少月份和日期

mysql - 使用 SQL,设计行为类似于其他表接口(interface)的表的最佳实践是什么?

mysql - 排列重复项并按顺序对记录进行编号 - MySQL

mysql - 使用临时表不起作用 - MYSQL

sql - bool 字段为 0 的 Count(*)

mysql - 在 MySQL 中查找 2 列中的重复值

sql如何为新手编写复杂的查询?