兩個選項:
- 問題1:如果你希望所有的
Player_ID
S的玩家所玩遊戲的最高數;或
- 查詢2:如果你只想要一個玩家玩的遊戲數量最多的玩家。
SQL Fiddle
的Oracle 11g R2架構設置:
CREATE TABLE Player
(
Player_ID PRIMARY KEY,
First_Name
) AS
SELECT 1, 'A' FROM DUAL
UNION ALL SELECT 2, 'A' FROM DUAL
UNION ALL SELECT 3, 'A' FROM DUAL;
CREATE TABLE Match
(
Match_ID PRIMARY KEY,
M_Type
) AS
SELECT 1, 'National' FROM DUAL
UNION ALL SELECT 2, 'International' FROM DUAL
UNION ALL SELECT 3, 'League' FROM DUAL;
CREATE TABLE Player_Score_Record
(
Player_ID NUMBER(1),
Match_ID NUMBER(1),
PRIMARY KEY (Player_ID, Match_ID),
FOREIGN KEY (Player_ID) REFERENCES Player (Player_ID),
FOREIGN KEY (Match_ID) REFERENCES Match (Match_ID)
);
INSERT INTO Player_Score_Record
SELECT 1,1 FROM DUAL
UNION ALL SELECT 1,2 FROM DUAL
UNION ALL SELECT 2,1 FROM DUAL
UNION ALL SELECT 2,2 FROM DUAL
UNION ALL SELECT 2,3 FROM DUAL
UNION ALL SELECT 3,2 FROM DUAL
UNION ALL SELECT 3,3 FROM DUAL;
查詢1:
WITH num_games AS (
SELECT r.Player_ID, COUNT(1) AS number_of_games_played
FROM Player_Score_Record r
INNER JOIN
Match m
ON (r.Match_ID = m.Match_ID)
WHERE m.M_Type IN ('National', 'International')
GROUP BY r.Player_ID
)
SELECT Player_ID
FROM num_games
WHERE number_of_games_played = (SELECT MAX(number_of_games_played)
FROM num_games)
Results :
| PLAYER_ID |
|-----------|
| 1 |
| 2 |
查詢2:
WITH num_games AS (
SELECT r.Player_ID, COUNT(1) AS number_of_games_played
FROM Player_Score_Record r
INNER JOIN
Match m
ON (r.Match_ID = m.Match_ID)
WHERE m.M_Type IN ('National', 'International')
GROUP BY r.Player_ID
ORDER BY number_of_games_played DESC, r.Player_ID
)
SELECT Player_ID
FROM num_games
WHERE ROWNUM = 1
Results:
| PLAYER_ID |
|-----------|
| 1 |
來源
2013-11-24 01:00:56
MT0
眼看着表結構會有所幫助,我想。 – slhck
非常感謝,這是我第一次在這裏發佈問題。我很震驚,當我幾分鐘前發佈它時,我正在尋找方法來做到這一點 – user3025012
您的子查詢是否按預期工作? – Adarsh