0

我有下表:

Season  Name1   Goal1   Name2   Goal2   Name3   Goal3
1990    Smith   2       Abel    1       John    3
1990    Smith   1       Abel    1       John    1
1990    John    0       Smith   2       Abel    5
1991    John    1       Smith   1       Abel    2
1991    Abel    2       John    0       Smith   0
1992    Abel    3       John    0       Smith   1

Season 表示一个足球赛季,name1,name2 表示球员在给定比赛中的位置 Goal1 表示 Name1 的进球数

我想为每个赛季的每个名字生成一个列表,他们打了多少次以及他们的进球数。像这样的东西:

Abel 1990 3 games played 7 goals scored
Abel 1991 2 games played 4 goals scored 
Abel 1992 1 games played 3 goals scored 
John 1990 3 games played 2 goals scored

任何帮助,将不胜感激!

4

3 回答 3

2
SELECT
    sub.player,
    sub.Season,
    Count(*) AS games_played,
    Sum(sub.goals) AS SumOfgoals
FROM
    (
        SELECT Season, Name1 AS player, Goal1 AS goals
        FROM YourTable
        UNION ALL
        SELECT Season, Name2, Goal2
        FROM YourTable
        UNION ALL
        SELECT Season, Name3, Goal3
        FROM YourTable
    ) AS sub
GROUP BY sub.player, sub.Season
ORDER BY sub.player, sub.Season;

请注意,您必须UNION ALL在该子查询中使用。如果您只是改为使用,则子查询结果集将只包含SeasonplayergoalUNION的每个组合的一行。但是,当一名球员在一个赛季的多场比赛中打进相同数量的进球时,您希望保留每一行,以便准确计算所参加的比赛和总进球数。

使用 Access 2007 中的示例数据,该查询会生成此结果集。

player Season games_played SumOfgoals
Abel     1990            3          7
Abel     1991            2          4
Abel     1992            1          3
John     1990            3          4
John     1991            2          1
John     1992            1          0
Smith    1990            3          5
Smith    1991            2          1
Smith    1992            1          1
于 2013-02-11T19:53:31.010 回答
1

好的,好吧,由于您没有共享您正在使用的 RDBMS,我认为这个(丑陋的)查询适用于其中的大多数:

SELECT  Name + ' ' + CAST(Season AS VARCHAR(4)) + ' ' +
        CAST(Games AS VARCHAR(4)) + ' games played ' + 
        CAST(Goals AS VARCHAR(4)) + ' goals scored' AS YourColumn
FROM (  SELECT Season, Name, SUM(Goals) AS Goals, COUNT(*) AS Games
        FROM (  SELECT Season, Name1 AS Name, Goal1 AS Goals
                FROM YourTable
                UNION ALL
                SELECT Season, Name2 AS Name, Goal2 AS Goals
                FROM YourTable
                UNION ALL
                SELECT Season, Name3 AS Name, Goal3 AS Goals
                FROM YourTable) AS A
        GROUP BY Season, Name) X

免责声明:这是一个丑陋的查询。

于 2013-02-11T19:09:05.777 回答
0

这真的很令人费解,但您可以编写一个内联查询,将所有内容放入适当的表格格式中,这样您就可以进行通常的聚合和分组。继续为 1 到 x 添加联合,具体取决于有多少列。

SELECT Season, Name, Sum(Goals)
FROM (SELECT Season, Name1 as Name, Goals1 as Goals        
        FROM table
      UNION
      SELECT Season, Name2 as Name, Goals2 as Goals        
        FROM table
      UNION
      SELECT Season, Name3 as Name, Goals3 as Goals        
        FROM table) newtable
GROUP BY Season, Name

于 2013-02-11T19:10:31.250 回答