Reputation: 3675
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?
Upvotes: 3
Views: 126
Reputation: 1186
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
Upvotes: 1
Reputation: 1438
You could do something like this (I named the table #a):
;WITH col3Sum AS
(
SELECT Col3, SUM(Col2) SUM3
FROM #a
WHERE col3 IS NOT NULL
GROUP BY col3
),
col1Sum AS
(
SELECT Col1, SUM(Col2) sum1
FROM #a
GROUP BY Col1
)
SELECT c1.Col1, ISNULL(c3.SUM3, c1.sum1) AS Col2
FROM col1Sum c1
LEFT JOIN col3Sum c3
ON c1.Col1 LIKE c3.Col3+'%'
ORDER BY c1.Col1
Upvotes: 0