[英]Sql query to fetch multiple data from multiple tables
Given the following tables:给定下表:
• Clients (ClientId, Name, Surname, Age) • 客户(ClientId、姓名、姓氏、年龄)
• Products (ProductId, Name, Price) • 产品(ProductId、名称、价格)
• Purchases (Purchaseld, Date, ClientId, Productid) • 购买(Purchaseld、日期、ClientId、Productid)
I need to write an SQL query that shows the quantity of purchases made by clients.我需要编写一个显示客户购买数量的 SQL 查询。 It must only show the clients who made more than 1 purchase.它只能显示购买超过 1 次的客户。 The result should contain the following fields: Full name (ie "john rambo"), Quantity of purchases.结果应包含以下字段:全名(即“john rambo”)、购买数量。
I have written this query but results are not coming correct我已经写了这个查询,但结果不正确
SELECT Concat(clients.name, clients.surname)
FROM clients
JOIN products
ON clients.name = products.name
JOIN purchases
ON products.productid = purchases.productid
GROUP BY clientid
HAVING Count(clientid) > 1
SELECT Concat(clients.name, ' ', clients.surname),
count(*) as number_of_orders
FROM clients
JOIN purchases
ON products.productid = purchases.productid
GROUP BY Concat(clients.name, ' ', clients.surname)
HAVING Count(clientid) > 1
As noted in the comments, your join to products doesn't make much sense - your asking to only return records where there's a product that matches a client's first name.如评论中所述,您加入产品没有多大意义 - 您要求仅返回与客户名字匹配的产品的记录。
CONCAT will glue the two fields together (eg "JohnRambo") CONCAT 将两个字段粘合在一起(例如“JohnRambo”)
It must only show the clients who made more than 1 purchase.它只能显示购买超过 1 次的客户。
Your question has no mention of products, so there is no need for that in the query:您的问题没有提及产品,因此查询中不需要:
SELECT CONCAT(c.name, c.surname)
FROM clients c JOIN
purchases p
ON p.ClientId = c.ClientId
GROUP BY c.ClientId, CONCAT(c.name, c.surname)
HAVING COUNT(*) > 1 ;
Note that the ClientId
presumably uniquely defines the clients -- not the names.请注意, ClientId
可能唯一地定义了客户端——而不是名称。 So the ClientId
should be part of the aggregation.所以ClientId
应该是聚合的一部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.