Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum two rows with different IDs

Tags:

sql

sql-server

I have the following data:

ID | Field A | Quantity
1  |  A   | 10 
2  |  B   | 20
3  |  C   | 30

I would like to sum the fields with ids 1 and 3 in a way that result will be:

ID | Field A | Quantity
1  |  A   | 40 
2  |  B   | 20

Sounds to me more like code manipulation rather than SQL, but still want to try it.

My DMBS is sql-server.

like image 332
Gabriel Muñumel Avatar asked Feb 20 '26 00:02

Gabriel Muñumel


2 Answers

you can try by using case when

select case when id in(1,3) then 'A' else 'B' end as field,sum(Quantity) as Quantity
from tablename group by case when id in(1,3) then 'A' else 'B' end
like image 95
Zaynul Abadin Tuhin Avatar answered Feb 22 '26 13:02

Zaynul Abadin Tuhin


I think simple aggregation does what you want:

select min(id) as id, min(fieldA) as fieldA, sum(quantity) as quantity
from t
group by (case when id in (1, 3) then 1 else id end);
like image 40
Gordon Linoff Avatar answered Feb 22 '26 12:02

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!