List all customers who spent 25% or less than the average amount spent on all invoices. For each customer, display their name and the amount spent to 6 decimal places. Order the result by the amount spent from high to low.

Schema

There are 2 tables: customer, invoice

customer
NameTypeDescription
idintThis is a primary key
customer_namevarchar(255)Name
city_idintCity ID
customer_addressvarchar(255)Address
contact_personvarchar(255) Can be NULL
emailvarchar(128)Email
phonevarchar(128)Phone number
is_activeintBoolean
invoice
NameTypeDescription
idintThis is a primary key
invoice_numbervarchar(255)Invoice number
customer_idintForeign key referencing customer.id
user_account_idintAccount ID
total_pricedecimal(8,2)Total price
Sample Data Tables
customer
idcustomer_namecity_idcustomer_addresscontact_personemailphoneis_active
1Drogerie Wien1Deckergasse 15AEmil Steinbach[email protected]0942342341
2Cosmetics Store4Watling Street 347Jeremy Corbyn[email protected]0939239231
3Kosmetikstudio3Rothenbaumchaussee 53Willy Brandt[email protected]09415622220
4Neue Kosmetik1Karlsplatz 2NULL[email protected]0941092531
5Bio Kosmetik2Motzstraße 23Clara Zetkin[email protected]0938258251
6K-Wien1Kärntner Straße 204Maria Rauch-Kallat[email protected]0934270021
7Natural Cosmetics4Clerkenwell Road 14BGlenda Jackson[email protected]0935551231
8Kosmetik Plus2Unter den Linden 1Angela Merkel[email protected]0947277271
9New Line Cosmetics4Devonshire Street 92Oliver Cromwell[email protected]0932024040
invoice
idinvoice_numbercustomer_iduser_account_idtotal_price
1in_25181b07ba800c8d2fc967fe991807d9741436
28fba0000fd456b27502b9f81e9d52481921000
33b6638118246b6bcfd3dfcd9be48759932360
4dfe7f0a01a682196cac0120a9adbb550521675
52a24cc2ad4440d698878a0a1a71f70fa629500
6cbd304872ca6257716bcab8fc43204d742150

The average amount spent by all customers is 2353.5. The threshold is 25% of the average amount i.e. 588.375. The customer ids of interest are 3 and 4.

SOLUTION:

				
					SELECT c.customer_name, FORMAT(SUM(i.total_price), 6) AS amount_spent
FROM customer c
JOIN invoice i ON c.id = i.customer_id
GROUP BY c.customer_name
HAVING SUM(i.total_price) <= (SELECT 0.25 * AVG(total_price) FROM invoice)
ORDER BY amount_spent DESC;