Postgres sum of values one per unique id
Answer a question I have to get a sum of the values from the column2, but I should calculate it only once per id. For example for the table below I need 5 + 10 + 7 and not 5 + 5 + 10 + 7 id column1 co
Answer a question
I have to get a sum of the values from the column2, but I should calculate it only once per id. For example for the table below I need 5 + 10 + 7 and not 5 + 5 + 10 + 7
id column1 column2
1 value1 5
1 value1 5
2 value1 10
3 value1 7
The latter I get by the following query, but I don't know how to adapt it to get the first sum. Should I filter the table beforehand like selecting all the distinct rows?
SELECT column1, sum(column2) FROM table group by column1;
Answers
You should consider cleaning up your data to remove the duplicate rows. But the following query should get the results you want by first grouping by id, column1
to remove the duplicates:
select column1, sum(column2)
from (select id, column1, min(column2) as column2
from tbl
group by id, column1) t
group by column1
更多推荐
所有评论(0)