简体   繁体   English

SQL - 根据其他列的某些条件查询 SUM

[英]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.例如,可以通过多种方式对客户端进行分类,在类别中,唯一重要的是 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.如果客户端至少有一行包含 HIT,则即使该特定行不是,也应始终将其归类为 HIT(例如(第 9 行)。正如您在我的数据集中看到的那样,客户端 A 的行都是 HIT和 NONE 但由于客户 A 至少有一条线是 HIT,所有的美元都应该归类为 HITS 美元。由于其他客户都没有 HIT 类别,他们所有的美元都将 go 变为 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.我正在尝试将其构建为 CASE 即。

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.显然,当类别为 NONE 时,这不会为客户 A 获得 HIT Dollars。 Any help would be greatly appreciated.任何帮助将不胜感激。

Thanks!谢谢!

You need more information.您需要更多信息。 I would suggest window functions:我建议 window 功能:

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 SQL 小提琴: 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 SQL 小提琴: http://sqlfiddle.com/#!9/8d403e/7/0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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