繁体   English   中英

SQL:如何在两个不同的条件上求和相同的值

[英]SQL: How to SUM the same value on two different criteria

可以说,我有下表记录了谁投资了公司列表。

Table: corporate_investments

company investor investment date
--------------------------------
CorpA    Alice     10       12/1
CorpB    Bob       20       12/2
CorpB    Sally     20       12/3 
CorpC    Cathy     30       12/4
CorpC    Alice     40       12/5
CorpC    Bob       10       12/6
CorpC    Bob       20       12/7

我将如何运行一个查询,以返回每个公司,鲍勃(VIP)的总投资以及对该公司的总投资?

我试过了

SELECT company,SUM(investment) as total investment
FROM corporate_investments
GROUP BY company

成功找到总投资额。

company    total_investment
---------------------------
CorpA           10
CorpB           40
CorpC          100

现在,我想为每个公司添加Bob的总金额。 我在SUM()函数本身内部需要类似子句的内容,但对如何执行此操作感到困惑。

使用条件聚合:

SELECT company, SUM(investment) as total,
       sum(case when investor = 'Bob' then investment else 0 end) as BobTotal
FROM corporate_investments
GROUP BY company;

您可以使用WITH ROLLUP获得每个投资者的滚动总额:

SELECT company, investor, SUM(investment) AS total
FROM corporate_investments
GROUP BY company, investor WITH ROLLUP

这将产生如下所示:

CorpA    Alice     10
CorpA    NULL      10
CorpB    Bob       20
CorpB    Sally     20
CorpB    NULL      40
CorpC    Alice     40
CorpC    Bob       30
CorpC    Cathy     30
CorpC    NULL     100

暂无
暂无

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

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