Max与SQL Server中的其他字段

Vin*_*uet 0 sql sql-server group-by max

这是我的查询:

SELECT id, id_gamut, position from operation
Run Code Online (Sandbox Code Playgroud)

它返回:

N°1)    id    id_gamut    position
        --------------------------
         1        19           1
         2        19           2
         3        19           3
         4        25           1
         5        25           2
         6        12           1
Run Code Online (Sandbox Code Playgroud)

我需要通过id_gamut将其与最大位置分组以获得如下结果:

N°2)    id    id_gamut    position
        --------------------------   
         3        19           3    
         5        25           2
         6        12           1
Run Code Online (Sandbox Code Playgroud)

然后我尝试了这样的事情:

SELECT gamut, Max(position) from(
SELECT id, gamut, position from operation) as req
GROUP BY gamut
Run Code Online (Sandbox Code Playgroud)

它工作,但我的问题是我真的需要在我的查询中有字段'id',但如果我这样添加它:

SELECT id, gamut, Max(position) from(
SELECT id, gamut, position from operation) as req
GROUP BY gamut,id
Run Code Online (Sandbox Code Playgroud)

我的小组被打破,结果为N°1

如何通过id_gamut对最大位置进行分组并具有"id"字段?

Sql*_*Zim 7

使用top with tiesrow_number()

select top 1 with ties
    id
  , id_gamut
  , position
from operation
order by row_number() over (
  partition by id_gamut 
  order by position desc
)
Run Code Online (Sandbox Code Playgroud)

或使用公共表表达式row_number()

;with cte as (
  select *
    , rn = row_number() over (
      partition by id_gamut 
      order by position desc
    )
  from operation
)
select 
    id
  , id_gamut
  , position
from cte
where rn = 1
Run Code Online (Sandbox Code Playgroud)

或者作为没有的子查询 cte

select 
    id
  , id_gamut
  , position
from  (
  select *
    , rn = row_number() over (
      partition by id_gamut 
      order by position desc
    )
  from operation
) s
where rn = 1
Run Code Online (Sandbox Code Playgroud)

或者 cross apply()

select distinct 
    x.id
  , o.id_gamut
  , x.position
from operation o
  cross apply (
    select top 1
        id
      , position
    from operation i
    where i.id_gamut = o.id_gamut
    order by position desc
    ) x
Run Code Online (Sandbox Code Playgroud)

或者使用not exists()(id_gamut如果有多个行具有相同的最大位置,则每行返回超过1行)

select *
from operation o
where not exists (
    select 1
    from operation i
    where i.id_gamut = o.id_gamut
     and i.position > o.position
    )
Run Code Online (Sandbox Code Playgroud)

或者使用not exists()(附加子句在多行具有相同最大位置的情况下返回最高id)

select *
from operation o
where not exists (
    select 1
    from operation i
    where i.id_gamut = o.id_gamut
      and (i.position > o.position
           or (i.position = o.position and i.id > o.id)
          )
  )
Run Code Online (Sandbox Code Playgroud)

rextester演示:http://rextester.com/INV77202