Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select a max row for each group in SQL

I want select countries with maximum value of 'Value' for a 'grpid'. Also already selected 'Country' should not be considered for other 'grpid' while checking the maximum. ( ie Country or grpid should not be repeated in the result )

SQL Fiddle

Result:

Country    grpid        Value           Row_number

US        49707        604456458         1
GB        5086         497654945         4 
CA        909          353500201         10
JP        231          198291290         15
like image 347
sajid Avatar asked Apr 01 '14 12:04

sajid


People also ask

Can we use max with GROUP BY in SQL?

The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.

How do I SELECT the maximum rows in SQL?

The SQL LIMIT clause restricts how many rows are returned from a query. The syntax for the LIMIT clause is: SELECT * FROM table LIMIT X;. X represents how many records you want to retrieve. For example, you can use the LIMIT clause to retrieve the top five players on a leaderboard.

Can we use SELECT * with GROUP BY?

When issuing a query with SELECT , you can end it with GROUP BY to group the selected columns by a particular column value. This is typically used in combination with aggregate functions, so that the results show the result of some aggregation function for rows with particular column values.

How do I limit 1000 rows in SQL?

You can easily change this limit by going to MySQL Workbench >> Edit >> Preferences >> SQL Queries tab. Over here you will option to Limit Rows. You can set this to very high value or uncheck the option. When you uncheck that option, it will retrieve all the rows from a query (equivalent to no limits).


2 Answers

try this query instead,

  WITH OrderedOrders AS
  (
     SELECT country,grpid,value,ROW_NUMBER() OVER(PARTITION BY country ORDER BY   country,value DESC) AS 'RowNumber' 
     FROM test1
  ) 
 select * from  OrderedOrders
 where RowNumber =1
like image 160
sakthi Avatar answered Oct 30 '22 17:10

sakthi


I believe this is what you're looking for:

SQL Fiddle

;with cte as 
(
  select 
      country,
      max(value) as MaxVal,
      min(row_number) as MinRow
  from test1
  group by Country
)
select 
  c.country,
  t.grpid,
  c.MaxVal,
  c.MinRow
from cte c
join test1 t
  on t.country = c.country 
  and t.value = c.MaxVal
  and t.row_number = c.MinRow
order by country, grpid
like image 42
Metaphor Avatar answered Oct 30 '22 18:10

Metaphor