2010-12-13 82 views
2

我有此信息的桌牌游戏:问题与SQL SELECT查询

- 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 ...

THANKS

回答

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 
+0

噢,你是更快:) – 2010-12-13 11:33:27

+0

你假设id_game是独一无二的 - 当然这可能是,但@Arturo没有指定 – 2010-12-13 11:53:33

+0

@JackPDouglas你说得对,但你假设裁判1!=裁判2 - 哪他也没有指定;) – 2010-12-13 11:56:59

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; 
0
SELECT ID_REFEREE1, count(*) as no_of_games 
FROM games 
GROUP BY ID_REFEREE1 
ORDER BY 2 
+0

如果您发布的是代码或XML,**请**在文本编辑器中突出显示这些行,然后单击编辑器工具栏上的“代码”按钮(101 010),以更好地格式化和语法突出显示它! – 2010-12-13 12:19:49

+0

用于和平格式化 – 2010-12-13 12:25:35

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 

你可以看到什么是错的?感谢

+0

事实上,我得到的错误是“#1248 - 每个派生表都必须有它自己的别名”。任何帮助? – Arturo 2010-12-13 13:54:35

+0

有些RDBMS(例如MySQL,postgres)坚持为每个子查询设置一个别名,因此''select * from(select * from games)'抛出一个错误,但是'select * from(select * from game)'因为g'很好。 – 2010-12-13 14:06:17