user1183013
user1183013

Reputation:

How to add a single column php/mysql

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.

Upvotes: 0

Views: 348

Answers (5)

Lasar
Lasar

Reputation: 5437

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.

Upvotes: 0

rs.
rs.

Reputation: 27427

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

Upvotes: 0

Jake
Jake

Reputation: 4374

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;

Upvotes: 0

Harshith J.V.
Harshith J.V.

Reputation: 887

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>;

Upvotes: 2

George Cummins
George Cummins

Reputation: 28906

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.

Upvotes: 2

Related Questions