Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find maximum value in a table

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
like image 638
Raja Avatar asked Apr 21 '15 14:04

Raja


People also ask

How do I get the maximum value from another column of a table in SQL?

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,...)

How do I find the maximum value of a row in SQL?

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 ).

How do you find the maximum value of GROUP BY?

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.


1 Answers

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;
like image 177
Peter Lang Avatar answered Sep 17 '22 09:09

Peter Lang