表格
Patient (patient_id, patient_name, gender, staff_no, ward_no)
Ward (ward_no, ward_name, number_of_beds)
查询
对于每个病房中至少有一名病人,给出病房号码和姓名,以及病房中的病人数和空床数。你的答案应该以空床的递减顺序呈现。
我写了以下SQL代码,服务器给了我一个错误:
无效使用聚合函数
SELECT ward.ward_no, ward.ward_name, COUNT(*) AS patient_count,
number_of_beds - COUNT(patient_id) AS empty_beds
FROM patient, ward
WHERE patient.ward_no = ward.ward_no
GROUP BY ward.ward_no, ward.ward_name, number_of_beds, empty_beds
HAVING COUNT(*) > 1
ORDER BY ward.ward_name
有人可以帮忙吗?我需要计算一些空床并将其作为一列返回。
提前致谢
答案 0 :(得分:1)
您不能按empty_beds
分组,除非您在SELECT语句中返回它(使用SQL Server)
SELECT ward.ward_no, ward.ward_name, COUNT(*) AS patient_count,
number_of_beds - COUNT(patient_id) AS empty_beds
FROM patient, ward
WHERE patient.ward_no = ward.ward_no
GROUP BY ward.ward_no, ward.ward_name, number_of_beds HAVING COUNT(*) > 1
ORDER BY ward.ward_name
答案 1 :(得分:0)
SELECT w.ward_no, ward_name, patient_count, number_of_beds - patient_count AS empty_beds
FROM (
SELECT ward_no, COUNT(*) AS patient_count
FROM patient
GROUP BY
ward_no
) p
JOIN ward w
ON w.ward_no = p.ward_no
ORDER BY
empty_beds DESC