我正试图完成这个Oracle SQL查询而没有运气。
“列出平均成本最低的部门。(提示:SELECT MIN(AVG(cost)
)只要在SELECT语句中没有组合其他列就有效。您可以将上面的子查询与另一个查询结合起来) “
我能够以平均成本显示Depts,但是当我尝试在MIN
工作时,它会中断。这是我到目前为止所做的。
SELECT DeptNo, AVG(projcost) FROM projects, clinicians WHERE clinicians.Clinicianno = projects.Clinicianno GROUP BY DeptNo;
这将为我提供depts及其AVG,但当我将AVG(projcost)
更改为MIN(AVG(projcost)
时,它会中断。提示是使它成为子查询但我无法弄清楚如何做到这一点。任何帮助将不胜感激。
答案 0 :(得分:3)
SELECT
MIN(q1.AvgProjCost)
FROM (SELECT
DeptNo,
AVG(projcost) as AvgProjCost
FROM projects, clinicians
WHERE clinicians.Clinicianno = projects.Clinicianno
GROUP BY DeptNo) q1
<强> EDITED 强> 假设我有以下部门项目费用
Department ProjectCost
1 15
1 15
1 15
2 16
2 16
3 17
3 17
4 18
这些项目成本将呈现以下平均值
Department Average
1 15
2 16
3 17
4 18
每个部门的最低平均值仍然是相同的结果集。
再次编辑
如果你真的必须拥有每个部门的最低平均值,那么这将有效
SELECT
q1.Dept,
MIN(q1.AvgProjCost)
FROM (SELECT
DeptNo,
AVG(projcost) as AvgProjCost
FROM projects, clinicians
WHERE clinicians.Clinicianno = projects.Clinicianno
GROUP BY DeptNo) q1
GROUP BY q1.Dept
然而,您很快就会意识到此结果集始终与
相同 SELECT
DeptNo,
AVG(projcost) as AvgProjCost
FROM projects, clinicians
WHERE clinicians.Clinicianno = projects.Clinicianno
GROUP BY DeptNo
再次编辑
获得平均项目成本最低的部门
SELECT
q1.Dept,
q1.AvgProjCost
FROM (SELECT
DeptNo,
AVG(projcost) as AvgProjCost
FROM projects, clinicians
WHERE clinicians.Clinicianno = projects.Clinicianno
GROUP BY DeptNo) q1
WHERE rownum = 1
ORDER BY AvgProjCost DESC
答案 1 :(得分:1)
试试这个:
WITH avgData AS
SELECT a.*,
RANK() OVER(ORDER BY avg_cost) RN
FROM
(
SELECT DeptNo,
AVG(projcost) avg_cost,
projects.ROWNUM rn
FROM projects,
clinicians
WHERE clinicians.Clinicianno = projects.Clinicianno
GROUP BY DeptNo
) a
SELECT *
FROM avgData
WHERE RN = 1
答案 2 :(得分:-1)
选择TOP 1 DEPTNO ,AVG(projcost) 从 项目 临床医生 哪里 临床医生.Clinicianno = projects.Clinicianno 通过...分组 DEPTNO 订购 AVG(projcost);
答案 3 :(得分:-1)
试试这个......
样本数据
DEPTNO| AVG_COST
100 |8601.333333
30 |4150
90 |19333.33333
20 |9500
70 |10000
110 |10154
50 |3475.555556
80 |8955.882353
40 |6500
60 |5760
10 |4400
SELECT DEPTNO,AVG_COST
FROM
(SELECT P.DEPTNO,
(AVG(C.COST)) AVG_COST
FROM PROJECTS P,
CLINICIANS C
WHERE P.DEPTNO=C.DEPTNO
GROUP BY P.DEPTNO
)
WHERE AVG_COST=
(SELECT MIN(AVG_COST)
FROM
(SELECT P.DEPTNO,
(AVG(C.COST)) AVG_COST
FROM PROJECTS P,
CLINICIANS C
WHERE P.DEPTNO=C.DEPTNO
GROUP BY P.DEPTNO
)
);
以上查询将为您提供以下结果
DEPTNO| AVG_COST
50 |3475.555556