Add Contents of Column

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

Add Contents of Column

Post by Skara »

Err.. I think I've done this before, but I don't remember how, and I can't find anywhere that says how.

Say you have a table as so...

Code: Select all

| 2 | 3 | 4 |
| 4 | 6 | 9 |
| 1 | 6 | 3 |
...
How would you add up a row in the query? e.g.

SELECT sum_of_contents(row2) AS blah;
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

you'd have to add each field together... I'd prefer to (if I had to use a single row for this) do the math in PHP.. or rebuild the table such that each record is a single "column" value and use it's aggregate functions..
yakasha
Forum Newbie
Posts: 10
Joined: Wed Aug 03, 2005 1:17 pm
Location: Las Vegas, NV
Contact:

Post by yakasha »

SELECT (col1 + col2 + col3) AS sum_of_cols FROM wherever;
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

Post by Skara »

dammit. :oops:
I meant to say add up the rows in a column. -_-'
As in...

| 2 | 3 | 4 |
| 4 | 6 | 9 |
| 1 | 6 | 3 |
...

Where it might add 3+6+6 or 2+4+1.

Columns and rows... dammit. :lol:
ryanlwh
Forum Commoner
Posts: 84
Joined: Wed Sep 14, 2005 1:29 pm

Post by ryanlwh »

SELECT SUM(col1) AS col1_total, SUM(col2) AS col2_total, SUM(col3) AS col3_total FROM whatever
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

Post by Skara »

voila! Thanks! ^^;
Post Reply