MySQL – How to Calculate Average Value of a Row

MySQL

I have a row which primary key value is 4 and there are another 8 values.
Those are 45 78 89 54 98 14 19 70. I want to select the average value, ie 58.37 from this row. How do I do this ?
The avg() function takes one argument only but i need to send 8 arguments.
My table picture is table with sample data

Best Answer

Unlike the last question, there is no AVERAGE() function other than GROUP BY aggregation.

This one can only be done by Dynamic SQL

Here are the Steps

  • Create the string bangla_1st+bangla_2nd+english_1st+english_2nd+...+science
  • Count the number of columns in the table that hold grades
  • Set up SQL to divide the sum of the columns by the count of the columns
  • Execute the SQL

Here is the Dynamic SQL for it

#
# Create a List of Columns
# Separated by the Plus Sign
#
SET group_concat_max_len = 1048576;
SELECT GROUP_CONCAT(column_name SEPARATOR '+') INTO @subject_sum
FROM information_schema.columns
WHERE table_schema=DATABASE() AND table_name='class6A'
AND column_name NOT IN ('roll','student_name');
#
# Count the Columns
#
SELECT COUNT(1) INTO @subject_count
FROM information_schema.columns
WHERE table_schema=DATABASE() AND table_name='class6A'
AND column_name NOT IN ('roll','student_name');
#
# Create the SQL
#
SET @sql = CONCAT('SELECT (',@subject_sum,')/',@subject_count);
SET @sql = CONCAT(@sql,' SubjectAverage FROM class6A WHERE roll=4');
#
# View the SQL
#
SELECT @sql Created_SQL_Statement\G
#
# Execute the SQL
#
PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s;

GIVE IT A TRY !!!