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