我必须找到最大进球者的名字和进球数。
GOAL_DETAILS(GOAL_ID,PLAYER_ID,TEAM_ID,GOAL_TIME)
PLAYER_MAST(PLAYER_ID,PLAYER_NAME)
我已经使用join
完成了此操作,但无法通过子查询完成。
请帮忙。
第一种方法:
SELECT PLAYER_ID,
PLAYER_NAME
FROM PLAYER_MAST
WHERE PLAYER_ID IN ( SELECT PLAYER_ID,
COUNT(PLAYER_ID)
FROM GOAL_DETAILS
GROUP BY PLAYER_ID
HAVING COUNT(PLAYER_ID)=(SELECT MAX(COUNT(*))
FROM GOAL_DETAILS
GROUP BY PLAYER_ID)
);
第二种方法:
SELECT PLAYER_ID,
PLAYER_NAME
FROM PLAYER_MAST
WHERE PLAYER_ID IN (SELECT PLAYER_ID,
COUNT(PLAYER_ID)
FROM GOAL_DETAILS
GROUP BY PLAYER_ID
HAVING COUNT(PLAYER_ID)=MAX(COUNT(PLAYER_ID))
);
第三种方法:
SELECT PLAYER_ID,
PLAYER_NAME
FROM PLAYER_MAST
WHERE PLAYER_ID IN (SELECT PLAYER_ID,
MAX(COUNT(*))
FROM GOAL_DETAILS
GROUP BY PLAYER_ID
) ;
我知道这些标签只会打印名称,而不是总得分目标,甚至不会打印姓名。
我在哪里做错了?
答案 0 :(得分:0)
我将在此处使用ROW_NUMBER
WITH cte AS (
SELECT p.PLAYER_ID, p.PLAYER_NAME, COUNT(*) AS cnt,
ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC) rn
FROM PLAYER_MAST p
INNER JOIN GOAL_DETAILS g
ON p.PLAYER_ID = g.PLAYER_ID
GROUP BY p.PLAYER_ID, p.PLAYER_NAME
)
SELECT PLAYER_ID, PLAYER_NAME
FROM cte
WHERE rn = 1;
如果您想捕获所有并列第一名的玩家,则将ROW_NUMBER
替换为RANK
。请注意,如果两个玩家可能碰巧使用相同的姓名,我将同时按PLAYER_ID
和PLAYER_NAME
进行汇总。
答案 1 :(得分:0)
with goal_details(goal_id,player_id,team_id,goal_time) as (
select 1, 1, 1, 10 from dual union all
select 2, 2, 2, 20 from dual union all
select 3, 2, 2, 30 from dual union all
select 3, 3, 3, 30 from dual
),
player_mast(player_id,player_name) as (
select 1, 'First' from dual union all
select 2, 'Second' from dual union all
select 3, 'Thirth' from dual
)
select
max(p.player_id) keep (dense_rank last order by count(*)) as max_scorer_id,
max(p.player_name) keep (dense_rank last order by count(*), p.player_id) as max_scorer_mame,
max(count(*)) as max_count
from goal_details d
join player_mast p on p.player_id = d.player_id
group by p.player_id, p.player_name;
MAX_SCORER_ID MAX_SC MAX_COUNT
------------- ------ ----------
2 Second 2
答案 2 :(得分:0)
我在哪里做错了?
您遇到ORA-00913: too many values
异常
这是因为您具有以下语法:
WHERE value1 IN ( SELECT value1, value2 ....
和您的IN
过滤器的左侧值必须与右侧列表中的值相同;因此,请删除子查询返回值的COUNT(PLAYER_ID)
部分:
WHERE PLAYER_ID IN ( SELECT PLAYER_ID FROM ....
然后您的第一次尝试应该起作用:
SELECT PLAYER_ID,
PLAYER_NAME
FROM PLAYER_MAST
WHERE PLAYER_ID IN ( SELECT PLAYER_ID
FROM GOAL_DETAILS
GROUP BY PLAYER_ID
HAVING COUNT(PLAYER_ID)=(SELECT MAX(COUNT(*))
FROM GOAL_DETAILS
GROUP BY PLAYER_ID)
);