按集合函数分组

时间:2016-06-15 20:17:41

标签: sql sql-server

我正在尝试执行GROUP BY' TeamID'但是在插入GROUP BY子句后出现以下错误:

专栏' po.PlayerWeighting'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

我应该把GROUP BY子句放在哪里才能将所有团队权重分组到TeamID?

SELECT DISTINCT TeamID,
    CASE WHEN TeamID = 0 THEN 0 
    ELSE SUM(po.playerWeighting) OVER(PARTITION BY po.TeamID)
    END TeamWeight,
    ABS(CHECKSUM(NewID())) % 10 + 1 AS Form
    FROM(
        SELECT pl.*,
               ROW_NUMBER() OVER(PARTITION BY pl.TeamID, pl.Position ORDER BY NEWID()) AS Rnk
        FROM(
            SELECT DISTINCT p.PlayerID, p.Position, p.PlayerWeighting, p.FirstName, p.Surname, t.TeamID, t.TeamAbbreviation, f.WeekNumber
            FROM dbo.Fixture f
            INNER JOIN dbo.League l ON f.LeagueID = l.LeagueID
            INNER JOIN dbo.Team t ON l.LeagueID = t.LeagueID
            INNER JOIN dbo.Player p ON t.TeamID = p.TeamID
            WHERE f.WeekNumber = 1) 
            pl) po 
    WHERE (po.Position = 'GK' and po.rnk = 1) OR 
          (po.Position = 'DF' and po.rnk <= 4) OR
          (po.Position = 'MF' and po.rnk <= 4) OR
          (po.Position = 'FW' and po.rnk <= 2)
          GROUP BY TeamID

1 个答案:

答案 0 :(得分:3)

DISTINCT之后不需要GROUP BYSUM() OVER()是不必要的,因为已经有GROUP BY TeamID

SELECT TeamID,
    CASE WHEN TeamID = 0 THEN 0 
    ELSE SUM(po.playerWeighting)
    END TeamWeight,
    ABS(CHECKSUM(NewID())) % 10 + 1 AS Form
    FROM
    ((...) po
    ) t
WHERE ...
GROUP BY TeamID