简体   繁体   中英

Who bought the biggest amount of a product in one order

I have 2 tables

  • CUSTOMERS (ID, FIRSTNAME, LASTNAME, ADDRESS);
  • ORDERS (ID, PRODUCT_NAME, PRODUCT_PRICE, DATE_ORDER DATE, ID_CUSTOMER, AMOUNT);

Get the first and last names of the customers who bought the biggest amount of a product in one order.

The orders without customer should not be considered. Please sort by FIRSTNAME and LASTNAME

Select firstname, lastname, amount
from customers
left Join orders on customers.id = orders.id_customer
group by firstname,lastname
having max(amount);

What am I missing? Thanks

There are many ways to skin this cat. This is one possibility:

select distinct c.firstname,c.lastname,o.amount 
from customers  c
     left join orders o on o.customer_id = c.id
where o.amount = (select max(amount)
                  from orders
                 )

There may be more than one row returned if multiple customers share the maximum order amount

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM