TABLE1:
SUBJECTS TYPE COST
--------- ------- ----
Subject 1 Math 12
Subject 2 English 13
Subject 3 Math 15
Subject 4 Math 13
Subject 5 English 14
我正在尝试计算每个主题的“类型”的平均成本。 因此对于主题1,查询输出应为
Subject 1, Math, 12, 13.33
最后一个是13.33,因为所有数学“类型”的平均值是([12 + 15 + 13] / 3)
到目前为止,我有这个:
SELECT Subjects, Type, Cost,
(SELECT AVG(Cost) FROM TABLE1)
FROM TABLE1;
我应该在这里进行内部联接还是在选择平均查询中按“类型”进行分组?谢谢!
答案 0 :(得分:1)
SELECT x.s1 SUBJECTS, x.t1 TYPE,Avg(c2) aVG_COST
FROM
(SELECT a.subjects s1,a.types t1,a.cost c1 ,b.subjects s2,b.types t2,b.cost c2
FROM TABLE1 a,TABLE1 b
WHERE a.types=b.types ) x
GROUP BY x.s1,x.t1 ORDER BY X.S1;
答案 1 :(得分:0)
以下是使用连接执行此操作的方法:
SELECT t1.*, t2.avg_cost
FROM TABLE1 t1
INNER JOIN
(
SELECT Type, AVG(Cost) AS avg_cost
FROM TABLE1
GROUP BY Type
) t2
ON t1.Type = t2.Type
如果您感觉更冒险,可以尝试使用AVG()
作为分析函数:
SELECT t.*,
AVG(t.cost) OVER (PARTITION BY t.Type) avg_cost
FROM TABLE1 t
答案 2 :(得分:0)
您可以在没有使用分析函数的自联接的情况下执行此操作:
SELECT t.*,
AVG( cost ) OVER ( PARTITION BY type ) As avg_cost
FROM table1 t