您首先必须确定所有种族,其价值等于同名种族的最大值。
SELECT
[r1].[Name],
[r1].[Value],
[r1].[Prize]
FROM [Races] [r1]
WHERE [r1].[Value] > 20
AND [r1].[Value] =
(SELECT MAX([r2].[Value])
FROM [Races] [r2]
WHERE [r2].[Name] = [r1].[Name])
这可能会产生具有相同名称、价值和奖品的多个种族。所以将它们分组:
SELECT
[r1].[Name],
[r1].[Value],
[r1].[Prize]
FROM [Races] [r1]
WHERE [r1].[Value] > 20
AND [r1].[Value] =
(SELECT MAX([r2].[Value])
FROM [Races] [r2]
WHERE [r2].[Name] = [r1].[Name])
GROUP BY
[r1].[Name],
[r1].[Value],
[r1].[Prize]
然后总结奖品:
SELECT
SUM([sub].[Prize]) AS [TotalPrizes],
COUNT(*) AS [NumberOfRaces]
FROM
(
SELECT
[r1].[Name],
[r1].[Value],
[r1].[Prize]
FROM [Races] [r1]
WHERE [r1].[Value] > 20
AND [r1].[Value] =
(SELECT MAX([r2].[Value])
FROM [Races] [r2]
WHERE [r2].[Name] = [r1].[Name])
GROUP BY
[r1].[Name],
[r1].[Value],
[r1].[Prize]
) AS [sub]
这是一个小提琴。(我将服务器类型设置为 MS SQL 2008,但我认为这不会成为这种情况/查询的问题)。