Search code examples
mysqlsqljoingreatest-n-per-group

How to select customer names with maximum invoice value


I have 2 tables

Customers
----------------
ID  | Name 
----+-----------
123 | Name1
456 | Name2
789 | Name3
----------------


Invoices
------------------
ID  | Value
----+-------------
123 | 1000
456 | 500
789 | 1000
------------------

I want to select customer names with the maximum invoice value


Solution

  • Test against the max value

    select c.name , i.value
    from customers c
    join invoices i on i.id = c.id
    where i.value = (select max(value) from invoices);
    
    +-------+-------+
    | name  | value |
    +-------+-------+
    | Name1 |  1000 |
    | Name3 |  1000 |
    +-------+-------+
    2 rows in set (0.001 sec)