MySQL - 选择所有客户和每个客户的总订单和总价值

时间:2013-03-01 17:36:02

标签: mysql sql select join

对于每个客户,我想返回:id,name,total_orders,total_value

客户:

╔════╦═════════════╗
║ ID ║    NAME     ║
╠════╬═════════════╣
║  1 ║ John Smith  ║
║  2 ║ Jim Jimmers ║
╚════╩═════════════╝

订单:

╔═══════╦══════════╦═══════╗
║  ID   ║ CUSTOMER ║ VALUE ║
╠═══════╬══════════╬═══════╣
║ 34656 ║        1 ║    20 ║
║ 37345 ║        2 ║    25 ║
║ 38220 ║        1 ║    15 ║
║ 39496 ║        1 ║    38 ║
║ 41752 ║        1 ║     9 ║
║ 43734 ║        2 ║    20 ║
╚═══════╩══════════╩═══════╝

如何选择以下结果:

╔════╦═════════════╦═════════════╦═════════════╗
║ ID ║    NAME     ║ TOTALORDERS ║ TOTAL_VALUE ║
╠════╬═════════════╬═════════════╬═════════════╣
║  1 ║ John Smith  ║           4 ║          82 ║
║  2 ║ Jim Jimmers ║           2 ║          45 ║
╚════╩═════════════╩═════════════╩═════════════╝

3 个答案:

答案 0 :(得分:7)

SELECT  a.ID,
        a.Name,
        COUNT(b.Customer) totalOrders,
        SUM(b.value) total_value
FROM    Customers a
        LEFT JOIN Orders b
            ON a.ID = b.Customer
GROUP   BY a.ID,
        a.Name

OR

SELECT  a.ID,
        a.Name,
        COUNT(b.Customer) totalOrders,
        COALESCE(SUM(b.value), 0) total_value
FROM    Customers a
        LEFT JOIN Orders b
            ON a.ID = b.Customer
GROUP   BY a.ID,
        a.Name

要进一步了解联接,请访问以下链接:

结果,

╔════╦═════════════╦═════════════╦═════════════╗
║ ID ║    NAME     ║ TOTALORDERS ║ TOTAL_VALUE ║
╠════╬═════════════╬═════════════╬═════════════╣
║  1 ║ John Smith  ║           4 ║          82 ║
║  2 ║ Jim Jimmers ║           2 ║          45 ║
╚════╩═════════════╩═════════════╩═════════════╝

答案 1 :(得分:0)

此查询应提供您的deriderated输出:

SELECT c.id, c.name, count(*) AS total_orders, sum(o.value) AS total_value
FROM Customers AS c
     LEFT JOIN Orders AS o ON c.id = o.customer
GROUP BY c.id

答案 2 :(得分:0)

使用内部联接,然后通过分组用户ID来使用总和。

SQL连接用于通过等式点合并表,您应该看一下这个http://dev.mysql.com/doc/refman/5.0/en/join.html

抱歉,我现在没有mysql服务器,就像这样:

选择id,name,sum(value)from(select customers.id as id,customers.name as name,orders.value as customers from customer inner join orders on customers.id = orders.customer)group by id < / p>

几乎可以肯定不是很正确,但在某个地方很近。