1

Given the following tables:

• Clients (ClientId, Name, Surname, Age)

• Products (ProductId, Name, Price)

• Purchases (Purchaseld, Date, ClientId, Productid)

I need to write an SQL query that shows the quantity of purchases made by clients. It must only show the clients who made more than 1 purchase. The result should contain the following fields: Full name (i.e. "john rambo"), Quantity of purchases.

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 
8
  • 1
    What do you see instead of what you expect? Commented Aug 10, 2020 at 9:31
  • 3
    clients.name = products.name this looks strange Commented Aug 10, 2020 at 9:32
  • 1
    I have written this query but results are not coming correct The only result which can be produced by your query in its primay state (before M Khalid Junaid's edition) is "Syntax error". Commented Aug 10, 2020 at 9:32
  • 1
    Can you provide a db-fiddle.com ? so we could easily play with your datas. Commented Aug 10, 2020 at 9:32
  • 1
    The table Products not needed to be used in described task. Join Clients and Purchases (use correct columns for joining), group by client and count purchases (not clients). Commented Aug 10, 2020 at 9:33

2 Answers 2

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 (e.g. "JohnRambo")

Sign up to request clarification or add additional context in comments.

1 Comment

SELECT Concat(clients.name, ' ', clients.surname), count(*) as number_of_orders FROM clients JOIN purchases ON Clients.clientid=Purchases.clientid GROUP BY clientid HAVING Count(clientid) > 1
0

It must only show the clients who made more than 1 purchase.

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. So the ClientId should be part of the aggregation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.