S.Patil
S.Patil

Reputation: 31

sql query to sum of same id but different value?

sql query to sum of same id but different value??.... I am trying to calculate sum of same id...following is my table

id        barter_value
2           50,000
2           1,50,000
3           47,000
3           55,000
3           50,00,000

I want output like

id       barter_value
2          2,00,000
3          51,00,2000


select a.buyer_id, 
       a.prod_barter_val 
       from add_to_cart as a
       join(select buyer_id, 
            sum(prod_barter_val) as total 
            from add_to_cart group by buyer_id) as b 
            on a.buyer_id = b.buyer_id;

Upvotes: 3

Views: 7032

Answers (3)

Filip Koblański
Filip Koblański

Reputation: 9988

You're almost there, just change the sql statment (b.total):

select buyer_id, 
   sum(prod_barter_val) as total 
   from add_to_cart
   group by buyer_id

Upvotes: 2

TolMera
TolMera

Reputation: 416

SELECT id, SUM(barter_value) as 'total' FROM table GROUP BY id

What this does: Selects all the ID's and the barter values from the table. Then the GROUP BY takes effect, and all ID's that are equal are joined into one row.

Without the SUM you would end up with just a random value in the barter_value column, but with SUM it adds all the rows together for the ID's (seperately) and puts that in the total column.

Upvotes: 2

Vasan
Vasan

Reputation: 4956

You can just do like:

select buyer_id, sum(prod_barter_val) from add_to_cart group by buyer_id

Upvotes: 3

Related Questions