4

对于每个客户,我想返回: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 ║
╚════╩═════════════╩═════════════╩═════════════╝
4

3 回答 3

9
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

或者

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 ║
╚════╩═════════════╩═════════════╩═════════════╝
于 2013-03-01T17:38:22.030 回答
0

此查询应提供您的贬低输出:

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
于 2013-03-01T17:39:20.277 回答
0

使用内部联接,然后通过对用户 ID 进行分组来求和。

SQL join 用于通过相等点合并表,你应该看看这个http://dev.mysql.com/doc/refman/5.0/en/join.html

抱歉,我现在没有 mysql 服务器 bu 是这样的:

select id, name, sum(value) from (select customers.id as id, customers.name as name, orders.value as value from customers inner join orders on customers.id = orders.customer) group by id

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

于 2013-03-01T17:46:45.177 回答