2

桌子:

Name | Value | Prize
Race1   32      5
Race1   22      5
Race1   30      5
Race2   11      5
Race2   12      5
Race2   31      5

我想查询的是,当我定义Value20+ 时,将根据谁Value更高,将唯一的比赛(Race1,Race2)选择到我的结果中。奖金应该加起来。

所以当我做元查询时:select sum(Prize) biggestValueUniqueRaces where value > -20 我得到:

查询返回:

Prize
  10

考虑到这两行的地方:

Name | Value | Prize
Race1   32      5
Race2   31      5
4

2 回答 2

2

您首先必须确定所有种族,其价值等于同名种族的最大值。

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,但我认为这不会成为这种情况/查询的问题)。

于 2013-01-13T19:23:26.053 回答
1

编辑重新评论

SELECT Sum(Races.Prize) As Total
FROM Races INNER JOIN (SELECT r.[Name], Max(r.[Value]) AS MaxOfValue
FROM Races r WHERE [Value]>20
GROUP BY r.[Name])  AS q 
ON (Races.Value = q.MaxOfValue) AND (Races.Name = q.Name);

或者

SELECT SUM(races.prize) AS SP
FROM   races
WHERE  races.id IN (
    SELECT id
    FROM   races r
    WHERE  r.name = races.name
    AND VALUE = (
       SELECT Max(VALUE)
       FROM   races s
       WHERE  s.[name] = r.name
       AND VALUE > 20 ))
于 2013-01-13T18:02:05.660 回答