epr8n
epr8n

Reputation: 45

mySQL sum by value

I'm new to using SQL and have the following table:

TableA

id|fk|value
-----------
1 |1 |100  
2 |1 |200  
3 |2 |300  
4 |2 |400  

I'm trying to, in another table, display the following:

TableB

id|sum
------
1 |300  
2 |700  

Where row i in TableB corresponds to the sum of all fk = i in TableA.

Can anybody point me in the right direction? Thanks!

Upvotes: 0

Views: 75

Answers (2)

Wirus
Wirus

Reputation: 1190

I assume TableB is just query result, not SQL table. Then you need a query like

select fk, sum(value)
from tableA
group by fk

If you want to create separate table, then you may just do

create table TableB as SELECT_ABOVE

You don't need to specify columns for new table, since they will be taken from select

Upvotes: 6

Mahesh Sambu
Mahesh Sambu

Reputation: 349

  create tableB(fk int, sum int)
  select fk, sum(value) 
  into #tableB 
  from 
  tableA 
  group by fk    
  • this shows:
  • TableB
  • id|sum
  • 1 |300
  • 2 |700

Upvotes: 0

Related Questions