Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.
Moderator: General Moderators
someberry
Forum Contributor
Posts: 172 Joined: Mon Apr 11, 2005 5:16 am
Post
by someberry » Wed Jul 19, 2006 8:15 am
Hi, does anyone know if it is possible to add values of multiple rows together? For instance:
Code: Select all
+----------+
| values |
+----------+
| id |
| quantity |
+----------+
There are hundreds of rows in this table, but I only want to add up the first three rows, ID numbers 1, 2, and 3.
Does anyone know if this can be done?
Thank you,
someberry
GM
Forum Contributor
Posts: 365 Joined: Wed Apr 26, 2006 4:19 am
Location: Italy
Post
by GM » Wed Jul 19, 2006 8:31 am
Code: Select all
SELECT SUM(`quantity`) FROM `values` WHERE `id` IN ('1', '2', '3');
is one way, alternatively:
Code: Select all
SELECT SUM(`quantity`) FROM `values` ORDER BY `id` LIMIT 3;
should be another.
Hope this helps.
someberry
Forum Contributor
Posts: 172 Joined: Mon Apr 11, 2005 5:16 am
Post
by someberry » Wed Jul 19, 2006 8:41 am
I probably should have mentioned that I am doing this in an UPDATE query, and am selecting multiple columns in the same row. Let me show you the current SQL I have:
Code: Select all
mysql_query("UPDATE `stock`, `total`
SET total.1 =
stock.1 * 100 +
stock.2 * 100 +
stock.3 * 100 +
stock.4 * 100
WHERE stock.stock_id IN ('0', '1', '2', '3')
") or die(mysql_error());
I get no errors from the SQL, but it only ever uses the first row to update.
Thanks,
someberry.
someberry
Forum Contributor
Posts: 172 Joined: Mon Apr 11, 2005 5:16 am
Post
by someberry » Sun Jul 23, 2006 4:12 pm
Anyone have any ideas?
Thanks,
Someberry