In SQL Server 2008 I have a table CUSTOMERS that has two columns as:
ID, BALANCE
How can I write the query that selects the ID of the customer who has maximum balance, "in the most effective way"?
Option 1: ORDER BY BALANCE and SELECT TOP(1)
--> costs too much.
Option 2: Firstly Get MAX amount
, then make another query that uses the amount in where clause
--> costs too much and not seem reliable.
To find the maximum value of a column, use the MAX() aggregate function; it takes a column name or an expression to find the maximum value. In our example, the subquery returns the highest number in the column grade (subquery: SELECT MAX(grade) FROM student ).
The SQL MIN() and MAX() Functions The MIN() function returns the smallest value of the selected column. The MAX() function returns the largest value of the selected column.
Note: An incorrect revision of this answer was edited out. Please review all answers.
A subselect in the WHERE
clause to retrieve the greatest BALANCE
aggregated over all rows. If multiple ID
values share that balance value, all would be returned.
SELECT ID, BALANCE FROM CUSTOMERS WHERE BALANCE = (SELECT MAX(BALANCE) FROM CUSTOMERS)
Here's an option if you have multiple records for each Customer and are looking for the latest balance for each (say they are dated records):
SELECT ID, BALANCE FROM ( SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY DateModified DESC) as RowNum, ID, BALANCE FROM CUSTOMERS ) C WHERE RowNum = 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With