我正在尝试编写一个查询来划分这两个 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/