我有这样的数据集:
+---------+--------+--------+
| Student | Score1 | Score2 |
+---------+--------+--------+
| 1 | 23 | 40 |
| 2 | 12 | 10 |
| 3 | 54 | 90 |
+---------+--------+--------+我想计算每行两个分数的平均值。从理论上讲,这很简单--只需做(score1 + score2/2)即可。但是,如果其中一个值为NULL,必须广泛使用NVL,则会遇到问题。AVG()函数将为我处理所有这一切,但这是为平均多行而设计的。对同一行中的值有任何使用AVG的方法吗?
更新
这是我目前所拥有的,它涉及到所有的可能性(据我了解)。不过,我认为一定有更清洁的方法?
SELECT
T1.STUDENT,
T1.SCORE1,
T1.SCORE2,
(NVL(T1.SCORE1,0) + NVL(T1.SCORE2,0))/DECODE((NVL2(t1.SCORE1,1,0) + NVL2(t1.SCORE2,1,0)),0,NULL,(NVL2(t1.SCORE1,1,0) + NVL2(t1.SCORE2,1,0))) AS AVG_SCORE
FROM STUDENTS T1;发布于 2015-03-24 11:09:01
你的方法很好。我会把它写成:
select student,
((coalesce(score1, 0) + coalesce(score2, 0)) /
nullif(nvl2(score1, 1, 0) + nvl2(score2, 1, 0), 0)
) as score_avg这种方法(或者你问题中的方法)的优点是很容易增加分数。
也就是说,具有基本相同名称的列意味着您应该使用一个连接表而不是多个列。
发布于 2015-03-24 11:01:50
那这个呢?
select student,
case
when score1 is null and score2 is not null then score2
when score1 is not null and score2 is null then score1
when score1 is null and score2 is null then 0
else (score1 + score2)/2 end
from your_table发布于 2015-03-24 11:22:13
另一种方法是使用UNION ALL将分数列统一为一个,然后使用普通的AVG / GROUP BY
SELECT student, avg(score) AS score
FROM (SELECT T1.STUDENT,
T1.SCORE1 AS score
FROM STUDENTS T1
UNION ALL
SELECT T1.STUDENT,
T1.SCORE2 AS score
FROM STUDENTS T1)
GROUP BY student
ORDER BY studenthttps://stackoverflow.com/questions/29230585
复制相似问题