Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to group by and return sum row in Postgres

I am stuck here. I have row in Postgres like this:

id      amount a       5000 a       1500 a       500 b       2000 b       1000 c       4000 

How is the sql syntax to get result like this?

id      amount a       7000 b       3000 c       4000 
like image 226
kuslahne Avatar asked Nov 04 '11 03:11

kuslahne


People also ask

Can we use sum with GROUP BY?

SUM is used with a GROUP BY clause. The aggregate functions summarize the table data. Once the rows are divided into groups, the aggregate functions are applied in order to return just one value per group. It is better to identify each summary row by including the GROUP BY clause in the query resulst.

How do I sum values in PostgreSQL?

Summary. Use the SUM() function to calculate the sum of values. Use the DISTINCT option to calculate the sum of distinct values. Use the SUM() function with the GROUP BY clause to calculate the sum for each group.

How do I do an aggregate sum in SQL?

The SQL Server SUM() function is an aggregate function that calculates the sum of all or distinct values in an expression. In this syntax: ALL instructs the SUM() function to return the sum of all values including duplicates. ALL is used by default.

How do I create a sum function in PostgreSQL?

PostgreSQL SUM function is used to find out the sum of a field in various records. You can take the sum of various records set using the GROUP BY clause. The following example will sum up all the records related to a single person and you will have salary for each person.


1 Answers

SELECT id, SUM(amount) AS amount FROM yourtable GROUP BY id 
like image 113
Marc B Avatar answered Sep 28 '22 22:09

Marc B