Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I combine rows in postgres when a column value is the same, and sum another column based on the combined rows?

Given a table structure like this:

id | name | amount | other1 | other2 | other3

and sample data like:

1 | a | 40 | unrelevant data | ...
2 | a | 80 | unrelevant data | ...
3 | b | 30 | unrelevant data | ...
4 | b | 50 | unrelevant data | ...
5 | c | 20 | unrelevant data | ...
6 | c | 30 | unrelevant data | ...

I want my select result to squash rows and sum the amounts that get squashed like so, I don't care about lost data (rows that say unrelevant data):

1 | a | 120 | unrelevant data | ...
3 | b | 80  | unrelevant data | ...
5 | c | 50  | unrelevant data | ...

I tried something like this:

SELECT id, "name", SUM(amount), other1, other2, other3 FROM test_table
GROUP BY "name"

I got the error:

column "id" must appear in the GROUP BY clause or be used in an aggregate function

so I know I'm missing something.

like image 834
Davis Mariotti Avatar asked Sep 06 '25 22:09

Davis Mariotti


2 Answers

You can use max() for the id:

SELECT MAX(id), "name", SUM(amount), MAX(other1) . . .
FROM test_table
GROUP BY "name"
like image 87
Gordon Linoff Avatar answered Sep 09 '25 04:09

Gordon Linoff


You can consider something like this.

SELECT t1.id, t2.name, t1.amount, t2, t2.other1, t2.other2, t2.other3 
FROM (
    SELECT id, SUM(amount) as amount FROM test_table
GROUP BY id) as t1
LEFT JOIN test_table t2 on t2.id = t1.id
like image 26
Ed Bangga Avatar answered Sep 09 '25 04:09

Ed Bangga