Say in table A, we have application name and location where those applications are used.
I'm looking to find the location where an application is being used the most. In case of ties, both locations should be returned.
Table content:
Application Location
A xy
A xy
A ab
B xy
B ab
B ab
Expected output:
Application Max(Loc)
A xy
B ab
The MySQL Solution If you're working with MySQL, you can combine MAX() with the GREATEST() function to get the biggest value from two or more fields. Here's the syntax for GREATEST: GREATEST(value1,value2,...)
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 ).
SQL max() with group by on two columnsSELECT cust_city, cust_country, MAX( outstanding_amt ) FROM customer GROUP BY cust_country, cust_city; Relational Algebra Expression: Relational Algebra Tree: Here is a slide presentation of all aggregate functions.
This can be solved using the aggregation function RANK
. Use ROW_NUMBER
instead to return only one row per application in case of ties.
Example on SQL Fiddle.
SELECT application, location
FROM (
SELECT application, location,
RANK() OVER ( PARTITION BY application ORDER BY COUNT(*) DESC ) AS rn
FROM t
GROUP BY application, location
) x
WHERE rn = 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