I have a following table
Col1 Col2 Col3
A1 1 null
A1 2 null
B1 5 null
B2 6 null
M1 1 M
M2 2 M
M3 3 M
J1 1 J
J2 2 J
I want to sum Col2 based on Col1. The query will be like following,
select Col1, sum (Col2)
group by Col1
However, if Col3 has the same letter, I want sum up Col2 for all Col1. So the result table should be like
Col1 Col2
A1 3
B1 5
B2 6
M1 6
M2 6
M3 6
J1 3
J2 3
How do I change my query to get above table?
Edit after comment / update to question. I didn't know a clever way, seems like some others have one though.
select * from (
select Col1, SUM(Col2) Col2
from Table
where Col3 is null
group by Col1
union
select mainset.Col1, tmp.Col2
from Table mainset
join
(
select Col3, SUM(Col2) Col2
from Table
where Col3 is not null
group by Col3
) tmp on tmp.Col3 = mainset.Col3
where mainset.Col3 is not null
) fullset
order by fullset.Col1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With