SQL SELECT查询的问题

时间:2010-12-13 11:24:29

标签: sql

我有一张GAMES表,其中包含以下信息:

- Id_Game (int)
- Id_Referee1 (int)
- Id_Referee2 (int)

这些是一些行:

ID_GAME    ID_REFEREE1    ID_REFEREE2
1          1000           728
2          1004           813
3          728            1004
4          1004           1000

我希望列出裁判主持的比赛数量,无论是作为裁判1还是裁判2。在这种情况下,我希望按照游戏DESC的数量接收此列表顺序。

REFEREE    NUMBER OF GAMES
1004       3
728        2
1000       2
813        1

哪个是SQL查询?我不知道如何加入字段Id_Referee1和Id_Referee2 ...

感谢

4 个答案:

答案 0 :(得分:3)

我想:

select referee, count(*) from (
    select id_game, id_referee1 as referee
    from games
    union
    select id_game, id_referee2 as referee
    from games
)
group by referee

答案 1 :(得分:0)

为所有可能的行假设id_referee1!= id_referee2(可能使用检查约束):

select referee, count(*) as number_of_games 
from( select id_referee1 as referee from games 
      union all 
      select id_referee2 from games )
group by referee
order by count(*) desc;

如果您不想做出这样的假设:

select referee, count(*) as number_of_games 
from( select id_referee1 as referee from games 
      union all 
      select id_referee2 
      from games 
      where id_referee1 is null or id_referee1!=id_referee2 )
group by referee
order by count(*) desc;

答案 2 :(得分:0)

SELECT ID_REFEREE1, count( * ) as no_of_games
FROM games
GROUP BY ID_REFEREE1
ORDER BY 2

答案 3 :(得分:0)

我觉得有些问题是因为我的查询出错:

SELECT Referee, count(*) FROM 
(
  (SELECT Id_Game, Id_Referee1 as Referee FROM Games) 
  UNION ALL 
  (SELECT Id_Game, Id_Referee2 as Referee FROM Games)
) GROUP BY Referee

你能看出出了什么问题吗?致谢