如何 select 具有最大发票价值的客户名称

How to select customer names with maximum invoice value

我有2张桌子

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


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

我想select 具有最大发票价值的客户名称

我们也可以用子查询得到结果。 使用带有值和名称的 [] 括号。因为这是 SQL server

中的保留关键字
SELECT C.ID, C.[Name], I.[Value]
FROM Customers C WITH(NOLOCK)
JOIN (
       SELECT TOP 1 ID, [Value]
       FROM Invoices WITH(NOLOCK)
       ORDER BY [Value] DESC
      ) AS I
ON C.ID = I.ID

针对最大值进行测试

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)