简体   繁体   中英

SQL - query to SUM based on certain criteria from other columns

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 need more information. I would suggest window functions:

SELECT (CASE WHEN is_hit = 1 THEN 'HITS'
             ELSE 'NOT'
        END) as result,
       SUM(dollars) AS Sum_Dollars
FROM (SELECT dollars, 
             MAX(CASE WHEN category = 'HIT' THEN 1 ELSE 0 END) OVER (PARTITION BY client) as is_hit
      FROM t
     )
GROUP BY is_hit

SQL Fiddle: http://sqlfiddle.com/#!4/40351/6

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM