SQL连接表,所有客户共花费的总数

时间:2014-10-12 00:19:01

标签: mysql sql

我是SQL的新手,这是我一直在努力解决的问题:

我有这些表格:

客户(custID,firstname,familyname)

项目(itemID,unitcost)

lineitems(quantity,orderID,itemID)

订单(orderID,custID,日期)

我需要找到所有订单超过一个订单的名称和总支出。

SELECT SUM(items.unitcost*lineitems.quantity) AS "total_spent"
FROM orders
INNER JOIN customers
ON orders.custID=customers.custID
GROUP BY firstname
HAVING COUNT(DISTINCT orderID)>1
LIMIT 0,30

1 个答案:

答案 0 :(得分:2)

我认为您只需要继续joins

SELECT c.custId, c.firstname, SUM(i.unitcost*li.quantity) total_spent
FROM customers c
    JOIN orders o ON c.custId = o.custId
    JOIN lineitems li ON o.orderId = li.orderId
    JOIN items i ON li.itemId = i.itemId
GROUP BY c.custId, c.firstname
HAVING COUNT(DISTINCT o.orderID)>1
LIMIT 0,30