SQL:如何在两个不同的条件上使用相同的值

时间:2015-03-02 20:08:09

标签: mysql sql database sum

假设我有下表记录谁投资了公司名单。

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

我如何运行返回每家公司的查询,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()函数本身的一个子句,但我很困惑如何做到这一点。

2 个答案:

答案 0 :(得分:4)

使用条件聚合:

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

答案 1 :(得分:0)

您可以使用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