0

I'm trying to add a single column in a db query result. I've read about the SUM(col_name) as TOTAL, GROUP BY (col_name2). But is there a way i can only SUM the column without any GROUPing? I a case whereby all col_name2 are all unique.

For example... I have a result with the following col headers:

course_code

course_title

course_unit

score

grade

Assuming this have 12 rows returned into an HTML table. Now i want to perform SUM() on all the values (12 rows) for the column course_unit, in other to implement a GPA school grading system.

How can i achieve this.

Thanks.

2
  • if you read a little more, you will find that you can use sum without groupby to have a sum of all retrieved rows ;) Commented Mar 5, 2012 at 12:28
  • @dotunoyesanmi: Please see the answers below. Commented Mar 5, 2012 at 12:47

5 Answers 5

2
SELECT SUM(col_name) as 'total' FROM <table>

GROUP BY is required only if you want to sum subsets of the rows in the table.

Sign up to request clarification or add additional context in comments.

Comments

2

You can find sum or any aggregate db functions (such as count, avg, etc) for most cases without using group clause. Your sql query may look something like this:

SELECT SUM(course_unit) as "Total" FROM <table_name>;

Comments

0

As comments below have already pointed out: SELECT SUM(course_unit) AS total FROM your_table;. Note that this is a separate query to the one with which you retrieve the table data.

Comments

0

This does it in php. I'm not sure how to do it with pure sql

$query = "SELECT * FROM table";
$result = mysql_query($query);
$sum = 0;
while($row = mysql_fetch_assoc($result))
{
    $sum+= intval($row['course_unit']);
}

echo $sum;

Comments

0
SELECT 
course_code, 
course_title, 
course_unit, 
score, grade, 
(select sum(course_unit) from TableA) total
from TableA;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.