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

时间:2014-04-01 12:13:25

标签: sql sql-server sql-server-2008 tsql greatest-n-per-group

我希望选择的国家/地区的价值最高为'价值'对于一个' grpid'。也已经选择了#Country;#39;不应该考虑其他的' grpid'同时检查最大值。 (即不应在结果中重复国家或grpid)

SQL Fiddle

结果:

Country    grpid        Value           Row_number

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

3 个答案:

答案 0 :(得分:3)

我相信这是你正在寻找的:

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

答案 1 :(得分:2)

尝试此查询,

  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

答案 2 :(得分:0)

请试试这个查询

select 
    country,
    value,
    grpid,
    count(*) 
from test1 
group by  
    country,
    value,
    grpid 
order by 
    country,
    value desc
相关问题