从分组依据中排除列

时间:2018-12-10 09:05:48

标签: sql sql-server tsql

我有一张这样的桌子

enter image description here

我当前的查询

.toString()

问题: 我还需要选择季节,显然我需要将其添加到分组依据中,但是却给了我无法更改分组依据的意外结果。因为我只需要按stat_id分组即可,只能按季节进行分组。我需要获取max()记录的季节。有人可以帮我吗?

我什至尝试过

Select team, 
       stat_id, 
       max(statsval) as statsval 
from tbl 
group by team,
      statid

但是最长季节的使用并不完全正确。

例外结果

Select team, 
       stat_id, 
       max (seasonid),
       max(statsval) as statsval 
from tbl 
group by team,
         statid

4 个答案:

答案 0 :(得分:0)

尝试此操作并在完成分组后查找团队ID:

;with tmp as 
(
  select team, 
         stat_id, 
         max(statsval) as statsval 
  from tbl 
  group by team,
           statid
) 
select tmp.*, 
       tbl.seasonid 
from tmp join tbl 
on tmp.team = tbl.team and  tmp.statid = tbl.stat_id; 

答案 1 :(得分:0)

取决于您的SQL Server版本,只能使用Window函数来完成此操作:

SELECT DISTINCT  team
    , stat_id
    , max(statsval) OVER (PARTITION BY team, stat_id) statsval
    , FIRST_VALUE(season_id) OVER (PARTITION BY team, stat_id ORDER BY  statsval DESC)
FROM tbl

答案 2 :(得分:0)

使用Windows函数尝试此操作

Select distinct team, 
                statid, 
                max(statsval) OVER(PARTITION BY team,statid ORDER BY seasonid) as statid, 
                max(seasonid) OVER(PARTITION BY team,statid ORDER BY statid)
from tbl

答案 3 :(得分:0)

如果需要完整的行,则可以简单地使用相关的子查询:

Select t.*
from tbl t
where t.season = (select max(t2.season) 
                  from tbl t2
                  where t2.team = t.team and t2.statsval = t.statsval
                 );

tbl(team, statsval, season)上有一个索引,它的性能可能比其他选项好或更好。

一个性能较差(甚至带有索引)的有趣方法是:

select top (1) with ties t.*
from tbl t
order by row_number() over (partition by team, statsval order by season desc);