SQL:如何根据两个不同的条件对相同的值求和

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

假设我有以下 table 记录谁投资了公司列表。

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

我如何 运行 查询 returns 每家公司、Bob(他是 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