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.
You can use max()
for the id
:
SELECT MAX(id), "name", SUM(amount), MAX(other1) . . .
FROM test_table
GROUP BY "name"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With