如何像主查询一样应用子查询分组?
这是查询:
select a.clinic_no ,
b.CLINIC_DESC_A ,
a.doctor_no ,
c.STAFF_NATIVE_NAME ,
count(DISCHARGE_FROM_CLINIC) ,
(select count(patient_no) from trng.opd_visits_history WHERE event_date BETWEEN 20240815 and 20240822) as "Total"
from trng.opd_visits_history a , trng.hospital_clinics b , trng.hospital_staff c
WHERE event_date BETWEEN 20240815 and 20240822
and a.CLINIC_NO = b.CLINIC_NO
and a.DOCTOR_NO = c.STAFF_NO
and b.DOCTOR_NO = c.STAFF_NO
and a.HOSPITAL_NO = 720022
and b.HOSPITAL_NO = 720022
and c.HOSPITAL_NO = 720022
AND a.DISCHARGE_FROM_CLINIC = 1
group by a.clinic_no , a.doctor_no , b.CLINIC_DESC_A , c.STAFF_NATIVE_NAME
输出如下:
clinic no doctor no discharge from clinic total
10 22 5 1230
12 15 4 1230
16 19 7 1230
20 13 2 1230
我需要像这样按子查询进行分组:
select count(patient_no) from trng.opd_visits_history WHERE event_date BETWEEN 20240815 and 20240822 group by clinic_no , doctor_no
当我在子查询中使用 group by 时,它显示错误
ORA-01427 single row subquery returns more than one row
您正在尝试使用相关子查询,但是 - 您没有在其表与外部表之间应用任何关联。它 must 仅返回一行(值),但是 - 当您将
group by
子句放入其中时 - 它导致返回不止一行,并且出现错误。
类似这样的事情可能会做:
SELECT a.clinic_no,
b.CLINIC_DESC_A,
a.doctor_no,
c.STAFF_NATIVE_NAME,
COUNT (DISCHARGE_FROM_CLINIC),
(SELECT COUNT (patient_no)
FROM trng.opd_visits_history h
WHERE h.clinic_no = a.clinic_no --> this
AND h.doctor_no = a.doctor_no --> this
AND event_date BETWEEN 20240815 AND 20240822) AS "Total"
FROM trng.opd_visits_history a, trng.hospital_clinics b, trng.hospital_staff c
WHERE event_date BETWEEN 20240815 AND 20240822
AND a.CLINIC_NO = b.CLINIC_NO
AND a.DOCTOR_NO = c.STAFF_NO
AND b.DOCTOR_NO = c.STAFF_NO
AND a.HOSPITAL_NO = 720022
AND b.HOSPITAL_NO = 720022
AND c.HOSPITAL_NO = 720022
AND a.DISCHARGE_FROM_CLINIC = 1
GROUP BY a.clinic_no,
a.doctor_no,
b.CLINIC_DESC_A,
c.STAFF_NATIVE_NAME