比方说,我有3个表:约会,医生和部门。
约会:
id status doctor_id
---- --------- ---------
1 approved 1
2 cancelled 4
3 approved 4
4 approved 1
5 approved 4
6 NULL 5
7 approved 2
8 NULL 5
9 approved 4
10 approved 3
11 cancelled 1
12 NULL 4
13 approved 3
14 cancelled 1
15 approved 4
16 cancelled 4
17 cancelled 2
18 NULL 4
19 cancelled 1
20 cancelled 4
医生:
id name department_id
---- --------- -------------
1 John 1
2 Robert 2
3 Patricia 3
4 Mary 1
5 Susan 3
部门:
id name
---- ---------
1 Dermatology
2 Neurology
3 Radiology
我需要的是经过医生分组的皮肤科批准和取消(批准/(已批准+已取消)* 100)总数的批准预约百分比。
我使用了以下查询,这使我更接近解决方案。
SELECT COUNT(*) AS appointment_count,
doctors.name AS doctor_name,
appointments.status AS appointment_status
FROM appointments
LEFT JOIN doctors ON appointments.doctor_id = doctors.id
LEFT JOIN departments ON doctors.department_id = departments_id
WHERE departments.id = 1
GROUP BY doctors.id,
appointments.status
结果:
count doctor_name appointment_status
----- ----------- ---------
2 John approved
3 John cancelled
0 John NULL
4 Mary approved
3 Mary cancelled
2 Mary NULL
但我需要每位医生批准/(已批准+已取消)的百分比。所以结果应该是:
approved_percentage doctor_name
------------------- -----------
%40 John
%57 Mary
我怎样才能达到这样的效果?
答案 0 :(得分:1)
您只能由医生进行分组,然后使用count(if())这样的功能:
SELECT d.name, count(*), count(if(a.status = 'approved', 1, null)) approved_count,
count(if(a.status = 'approved', 1, null))/count(*) * 100 approved_percentage
FROM doctors d
INNER JOIN appointments a ON a.doctor_id = d.id
GROUP BY d.name
答案 1 :(得分:1)
在MySQL中,进行条件计数和平均值的最简单方法就是使用布尔表达式。这表明:
SELECT d.name, count(*),
SUM(a.status = 'approved') as approved_count,
AVG(a.status = 'approved') * 100 as approved_percentage
FROM doctors d INNER JOIN
appointments a
ON a.doctor_id = d.id
GROUP BY d.name;