MySQL:合并下一个重复的结果

时间:2017-09-15 13:20:42

标签: mysql

我有这个问题

SELECT
ip_clients.client_name, ip_invoice_amounts.invoice_balance as totals
FROM ip_clients
INNER JOIN ip_invoices ON ip_invoices.client_id = ip_clients.client_id
INNER JOIN ip_invoice_items ON ip_invoices.invoice_id = ip_invoice_items.invoice_id
INNER JOIN ip_invoice_amounts ON ip_invoice_items.invoice_id = ip_invoice_amounts.invoice_id

数据库示例 https://pastebin.com/c3iYNMkq

输出:

| client_name | totals  | 
|------------ | ------- |
| Client 1    | 400.00  |
| Client 2    | 500.00  |
| Client 1    | 124.00  |

我想将此设为客户端1 524 和客户端2 500 合并重复的总计并用总计打印一次

1 个答案:

答案 0 :(得分:1)

GROUP BY上的简单client_nameSUM上的invoice_balance应该有效:

SELECT 
    ip_clients.client_name, 
    SUM(ip_invoice_amounts.invoice_balance) AS totals
FROM ip_clients
    INNER JOIN ip_invoices ON ip_invoices.client_id = ip_clients.client_id
    INNER JOIN ip_invoice_items ON ip_invoices.invoice_id = ip_invoice_items.invoice_id
    INNER JOIN ip_invoice_amounts ON ip_invoice_items.invoice_id = ip_invoice_amounts.invoice_id
GROUP BY ip_clients.client_name