2

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

任何人都可以帮忙吗?我需要计算空床的数量并将其作为列返回。

提前致谢

4

2 回答 2

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
于 2013-04-30T16:23:25.077 回答
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
于 2013-04-30T16:26:03.743 回答