MySQL查询结合多个表的总和

时间:2017-07-06 18:36:49

标签: mysql sql join

我有以下查询尝试生成所有客户的列表,他们的项目,每个项目花费的时间,总发票金额和发票总数。

SELECT
    c.name as client,
    p.name as project,
    SUM(t.hours) as hours,
    SUM(ci.amount) as invoice_amount,
    COUNT(ci.id) as number_invoices
FROM
    projects p
    INNER JOIN client_master c ON c.harvest_id = p.client_id
    INNER JOIN timesheet t ON t.project_id = p.id 
    LEFT OUTER JOIN projects_contracts pc ON pc.project_id = p.id
    INNER JOIN contracts_invoices ci ON ci.contract_id = pc.contract_id
GROUP BY
    c.name,
    p.name
ORDER BY
    c.name, 
    p.name,
    t.hours

当我运行查询时,"小时"正确计算,但invoice_amount和number_invoices的总和/计数不是在上下文中加入项目,而是与表中的发票总数相关联。如果我注释掉其中一个sum()' s,那么我得到了正确的值,但是当它们都进入时都没有。

预期结果

客户A,项目1,1000,$ 10,000,2

客户A,项目2,5000,$ 5,000,1

客户B,项目1,100,$ 3000,1

实际结果

客户A,项目1,1000,$ 150,000,20

客户A,项目2,5000,$ 50,000,81

客户B,项目1,100,$ 83000,12

我已经尝试弄乱了分组和加入声明,但没有找到成功。有什么简单的我可以忽略或者我需要完全重写吗?

2 个答案:

答案 0 :(得分:0)

由于发票取决于合同,合同是可选的(左连接), 使该连接也成为左连接。

xhr.setRequestHeader("Authorization", "Token token='XXX'")

答案 1 :(得分:-1)

这可能不是最好的方式,但我敢打赌它有效

SELECT
    c.name as client,
    p.name as project,
    t.hours as hours,
    ci.amount as invoice_amount,
    ci.count as number_invoices
FROM
    projects p
    INNER JOIN client_master c 
        ON c.harvest_id = p.client_id
    INNER JOIN (SELECT project_id, SUM(hours) AS hours FROM timesheet GROUP BY project_id) t
        ON t.project_id = p.id 
    LEFT OUTER JOIN projects_contracts pc 
        ON pc.project_id = p.id
    LEFT OUTER JOIN (SELECT contract_id, SUM(amount) AS amount, COUNT(DISTINCT id) AS count FROM contracts_invoices GROUP BY contract_id) ci
        ON ci.contract_id = pc.contract_id
GROUP BY
    c.name,
    p.name
ORDER BY
    c.name, 
    p.name,
    t.hours