user1320260
user1320260

Reputation:

merge Database records when keys match and add values

I wish to select all records from a database and then combine matching keys and also adding their values.

Col1     col2 
-----  ------
ABC       2
ABA       3
ADD       1
AED       3
ABC       2
ABA       3
ADD       1
AED       3

So i would end up with

array("
    ABC  =>       4,
    ABA  =>       6,
    ADD  =>       2,
    AED  =>       6");

Upvotes: 0

Views: 41

Answers (1)

Sylvain Leroux
Sylvain Leroux

Reputation: 51990

This is basic GROUP BY application:

SELECT Col1, SUM(col2) FROM tbl GROUP BY Col1

See http://sqlfiddle.com/#!2/8d1f8/1 for an example

Upvotes: 3

Related Questions