簡體   English   中英

從分組依據中排除列

[英]Exclude columns from Group by

我有這樣的桌子

在此處輸入圖片說明

我目前的查詢

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

問題:我還需要選擇季節,顯然我需要將其添加到分組依據中,但是卻給了我無法更改分組依據的意外結果。因為我只需要按stat_id分組即可,只能按季節進行分組。 我需要獲取max()記錄的季節。 有人可以幫我嗎?

我什至試過

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

但這需要最長的季節,而並非完全正確的結果。

異常結果

+--------+--------+-------+---------+---------+
| season |  team  | round | stat_id | statval |
+--------+--------+-------+---------+---------+
|   2004 | 500146 |     3 |       1 |       5 |
|   2007 | 500147 |     1 |       1 |       4 |
+--------+--------+-------+---------+---------+

嘗試此操作並在完成分組后查找團隊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; 

根據您的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

使用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

如果需要完整的行,則可以簡單地使用相關的子查詢:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM