我有两个具有以下属性的表
DOCTORS OPERATIONS
D_ID DATE
Name TYPE
Specialiation DOCTORS_D_ID
PACIENTS_PACIENT_ID
我希望返回的doctores名称和ID超过每位医生的平均操作次数。
我创建了以下SQL命令
SELECT Name D_ID,COUNT(*) FROM DOCTORS
JOIN OPERATION
ON D_ID = DOCTORS_D_ID
GROUP BY D_ID,Name
HAVING COUNT(*) > ( SELECT AVG(COUNT(DOCTORs_D_ID))
FROM OPERATIONS GROUP by DOCTORS_D_ID )
此结果见下表
D_ID COUNTS(*)
Dr. Martin 3
在列D_ID中是名称而不是ID =表中只返回两个属性中的一个。如何从此命令返回 - name
和D_ID
?
答案 0 :(得分:2)
我不是嵌套聚合函数的粉丝。我只是直接计算平均值来做到这一点:
SELECT Name, D_ID, COUNT(*)
FROM DOCTORS JOIN
OPERATION
ON D_ID = DOCTORS_D_ID
GROUP BY D_ID, Name
HAVING COUNT(*) > (SELECT COUNT(*) / COUNT(DISTINCT DOCTORs_D_ID))
FROM OPERATIONS
);
答案 1 :(得分:1)
有一个问题是不计算平均没有操作的医生(在这种情况下,仅仅使用操作表[或与操作表的内部连接]的平均值将高于实际答案操作表中的操作次数和医生表中的医生数量。)
为了弥补这一点,你可以这样做:
SELECT Name,
D_ID,
num_operations
FROM ( SELECT Name,
D_ID,
COUNT( 1 ) OVER () AS num_doctors
FROM doctors ) d
LEFT OUTER JOIN
( SELECT DISTINCT
DOCTORS_D_ID,
COUNT( 1 ) OVER ( PARTITION BY DOCTORS_D_ID ) AS num_operations,
COUNT( 1 ) OVER () AS total_operations
FROM operations ) o
ON ( d.d_id = o.doctors_d_id )
WHERE num_operations > total_operations / num_doctors;
使用分析函数来计算计数而不是执行第三次表扫描,还有额外的好处。
答案 2 :(得分:0)
with num_operations as
select doctors_d_id,count( * ) as operations from operations
group by doctors_d_id and having count(*)>
(select avg(count(doctors_d_id) from operations group by doctors_d_id )
select doctors_d_id,operations,name from num_operation a, doctors b
where a.doctors_d_id=b.d_id