我有三张表格,内容如下。
表1:产品 - 列:产品名称,价格,产品ID
表2:客户 - 列:客户名称,客户ID,城市
表3:订单 - 列:订单ID,客户ID,产品ID
以下情景的查询应该是什么?
方案: 需要显示客户名称,各个客户的订单号,支付总价(各客户的所有订单总和)。
答案 0 :(得分:0)
尝试类似
的内容SELECT c.CustomerName,
count(o.orderId) [Orders Count],
SUM(p.Price) [Total Price]
FROM CUSTOMERS c
JOIN ORDERS o ON o.customer_id = c.customer_id
JOIN PRODUCTS p ON p.product_id = o.product_id
GROUP BY c.CustomerName
答案 1 :(得分:0)
试试这个:
SELECT c.name,COUNT(o.id),SUM(p.price)
FROM customers c
INNER JOIN orders o ON c.id = o.customer_id
INNER JOIN products p ON p.id = o.product_id
GROUP BY c.name;
您通过customer_id与订单一起加入客户;然后使用product_id与产品加入订单。
然后您只需GROUP BY c.name获取每个客户的COUNT(o.id)和SUM(p.price)的聚合值。
答案 2 :(得分:0)
以下内容如何:
SELECT c.[Customer Name], COUNT(DISTINCT o.[Order ID]), SUM(p.Price)
FROM Customers AS c
JOIN Orders AS o ON c.[Customer ID] = o.[Customer ID]
JOIN Products AS p ON o.[Product ID] = p.[Product ID]
GROUP BY c.[Customer Name]
唯一的问题是,Orders
表似乎缺少Quantity
字段。所以,在上面的例子中,我只是在总结价格。
另外,为了获得每个客户的订单数量,我在COUNT()函数中使用了distinct。如果单个订单可以指向多个产品,则需要执行此操作。否则你可以删除它。
答案 3 :(得分:0)
试试这个:
select c.customer_name, x.no_of_orders, y.total_price from customer c
left join (
select customer_id, COUNT(customer_id) as no_of_orders from orders
group by customer_id) x on c.customer_id = x.customer_id
left join (
select o.customer_id, SUM(p.price) as total_price from order o
inner join products p on o.productid = p.productid
group by customer_id) y on c.customer_id = y.customer_id