简体   繁体   English

如何在SQL中为每个组选择最大行

[英]How to select a max row for each group in SQL

I want select countries with maximum value of 'Value' for a 'grpid'. 我希望选择“价值”最大值的国家/地区作为“grpid”。 Also already selected 'Country' should not be considered for other 'grpid' while checking the maximum. 在检查最大值时,也不应考虑其他'grpid'选择'Country'。 ( ie Country or grpid should not be repeated in the result ) (即结果中不应重复国家或grpid)

SQL Fiddle SQL小提琴

Result: 结果:

Country    grpid        Value           Row_number

US        49707        604456458         1
GB        5086         497654945         4 
CA        909          353500201         10
JP        231          198291290         15

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 SQL小提琴

;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

Can you please try out this query 你能试试看吗?

select 
    country,
    value,
    grpid,
    count(*) 
from test1 
group by  
    country,
    value,
    grpid 
order by 
    country,
    value desc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM