I have an issue where I need to essentially categorically sum dollars based on criteria from different columns. For instance, there are multiple ways that a Client can be categorized and in the categories, the only one that matters is HIT. If a client has at least one line that contains HIT it should always be categorized as HIT even when that specific line isn't (example (line 9). As you can see in my data set, client A has lines that are both HIT and NONE but since Client A has at least one line that is HIT, all of the dollars should be categorized as HITS dollars. Since none of the other clients have HIT categories, all of their dollars would go into NOT.
CLIENT DOLLARS CATEGORY
A 12434 HIT
B 212 NONE
C 21 NONE
D 1231 NONE
B 784 NONE
A 43577 HIT
D 64 NONE
A 123 NONE
D 12 NONE
A 53 NONE
A 10 NONE
I'm trying to build this into a CASE ie.
SELECT CASE
WHEN category = 'HIT' THEN 'HITS'
WHEN category <> 'HIT' THEN 'NOT'
ELSE 'OTHER' END AS 'RESULT'
SUM(dollars) AS Dollars
FROM table 1
GROUP BY 'RESULT'
Obviously this won't pick up HIT Dollars for Client A when the category is NONE. Any help would be greatly appreciated.
Thanks!
You could join your table with a subquery that lists the hit clients:
select (case when (hits.client is null)
then 0
else 1
end) as hit,
sum(dollars) as Dollars
from t
left outer join ( select distinct client
from t
where category = 'HIT' ) hits
on t.client = hits.client
group by hit;
SQL fiddle: http://sqlfiddle.com/#!9/8d403e/7/0