2010-12-13 118 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