-1

I know this is probably a simple question since I'm still learning, but I am trying to find a SQL Select statement that will calculate the SUM of each row's pieces and weight IF their secondary IDs are the same. So the select is collapsing and getting the SUM of rows with the same secondary ID, while also returning the unique rows as well.

ID_a  ID_b  pieces  weight
--------------------------
1     1     10      20
2     1     20      30
3     2     40      40

Will result in

ID_b: 1  pieces: 30  weight: 50
ID_b: 2  pieces: 40  weight: 40

Thank you.

Kameros
  • 1
  • 2

3 Answers3

3

Group by the id_b and then you can use aggregate functions to sum up the values for each group

select id_b, sum(pieces), sum(weight)
from your_table
group by id_b
juergen d
  • 201,996
  • 37
  • 293
  • 362
0
select id_b,sum(pieces),sum(weight)
from table 
group by id_b
Adi
  • 232
  • 1
  • 9
0

Here is the query you're looking for:

SELECT TID_b
      ,SUM(pieces) AS [totalPieces]
      ,SUM(weight) AS [totalWeight]
FROM yourTable T
GROUP BY T.ID_b

Hope this will help you.

Joël Salamin
  • 3,538
  • 3
  • 22
  • 33