SQL新手,需要帮助。我试图计算4个科目的平均值,但是如果一个科目为零/ 0,那么它不会被包括在计算中。
Type Collation
Student_ID varchar(5)
Surname varchar(9)
First_Name varchar(7)
Ballet int(2)
Contemporary int(2)
Jazz int(2)
Tap int(2)
我已经能够使用下面的视图获得平均值,但无法弄清楚如何解决null/0
问题。
SELECT Student_ID, Surname, First_Name, BALLET_1, CONTEMPORARY_1, JAZZ_1, TAP_1, sum(BALLET_1+CONTEMPORARY_1+JAZZ_1+TAP_1 )/4 as Avg from tblassesstest group by Surname
答案 0 :(得分:0)
SELECT
(
SELECT COALESCE( nb1, 0 ) + COALESCE( nb2, 0 ) + COALESCE( nb3, 0 ) as ADDITION
)
/
(
SELECT
COALESCE(nb1 /nb1, 0)
+
COALESCE(nb2 /nb2, 0)
+
COALESCE(nb3 /nb3, 0)
AS DIVIDEBY
) AS AVG
FROM YOURTABLE
我认为这是最好的答案。 解释:
函数COALESCE用另一个值替换你的NULL,这里是0。
第二个选择(DIVIDEBY)计算非空的列数:
顶级"匿名" SELECT将每列(nb1,nb2,nb3)发送到所选表的两个子请求(YOURTABLE)
答案 1 :(得分:0)
SELECT Student_ID,Surname,First_Name,BALLET_1,CONTEMPORARY_1,JAZZ_1,TAP_1,
(
SELECT COALESCE( BALLET_1, 0 ) + COALESCE( CONTEMPORARY_1, 0 ) + COALESCE( JAZZ_1, 0 )+ COALESCE( TAP_1, 0 ) as ADDITION
)
/
(
SELECT
COALESCE(COALESCE(BALLET_1, 0) / COALESCE(BALLET_1, 0), 0)
+
COALESCE(COALESCE(CONTEMPORARY_1, 0) / COALESCE(CONTEMPORARY_1, 0), 0)
+
COALESCE(COALESCE(JAZZ_1, 0) / COALESCE(JAZZ_1, 0), 0)
+
COALESCE(COALESCE(TAP_1, 0) / COALESCE(TAP_1, 0), 0)
AS DIVIDEBY
) AS AVG
FROM tblassesstest
按姓氏分组