我有下表:
FileName | SubFileName | TotalPlayersCount |
-------------------------------------------
AAA | SF1 | 11 |
AAA | SF2 | 5 |
AAA | SF3 | 3 |
BBB | SF1 | 8 |
BBB | SF2 | 15 |
BBB | SF3 | 2 |
CCC | SF1 | 5 |
CCC | SF2 | 10 |
CCC | SF3 | 20 |
如您所见,每个
FileName
都有3个不同的SubfileName
('SF1','SF2','SF3')。每个
SubfileName
都有不同的TotalPlayersCount
值。我正在尝试从三个
TotalPlayersCount
中选择列SubfileName
的最大值,这是FOREACHFileName
。结果应该是:
FileName | SubFileName | TotalPlayersCount |
-------------------------------------------
AAA | SF1 | 11 |
BBB | SF2 | 15 |
CCC | SF3 | 20 |
我问了自己几个问题,这是我最近的一次:
select distinct FileName, max(TotalPlayersCount) AS TotalPlayersCount
from dbo.MyTestTable
group by FileName
这就是我得到的结果:
FileName | TotalPlayersCount |
------------------------------
AAA | 11 |
BBB | 15 |
CCC | 20 |
所以现在我错过了结果中的
SubfileName
。你能帮我找到丢失的东西吗?
提前谢谢。
最佳答案
简单的方法是,如果没有其他具有相同文件名且TotalPlayersCount更高的行,则使用NOT EXISTS
返回行:
select FileName, SubFileName, TotalPlayersCount
from dbo.MyTestTable t1
where not exists (select 1 from dbo.MyTestTable t2
where t2.FileName = t1.FileName
and t2.TotalPlayersCount > t1.TotalPlayersCount)
JOIN
版本,也许性能更好:select t1.FileName, t1.SubFileName, t1.TotalPlayersCount
from dbo.MyTestTable t1
JOIN (select FileName, max(TotalPlayersCount) as TotalPlayersCount
from dbo.MyTestTable
group by FileName) t2
ON t2.FileName = t1.FileName
and t2.TotalPlayersCount = t1.TotalPlayersCount
两个查询都将返回两行,以防出现平局!