gpt4 book ai didi

sql - 您可以对同一行中的值运行 Oracle 的 AVG() 函数吗?

转载 作者:行者123 更新时间:2023-12-04 21:19:15 25 4
gpt4 key购买 nike

我有一个这样的数据集:

+---------+--------+--------+
| Student | Score1 | Score2 |
+---------+--------+--------+
| 1 | 23 | 40 |
| 2 | 12 | 10 |
| 3 | 54 | 90 |
+---------+--------+--------+

我想计算每行 2 个分数的平均值。理论上这很简单 - 只需做 (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;

最佳答案

那这个呢:

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

关于sql - 您可以对同一行中的值运行 Oracle 的 AVG() 函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29230585/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com