我有两列(都是主要的)[PLAYER_ID] [LEAUGE_ID]
类似的东西:
Player_id League_id
2139 8
2153 8
2302 10
2441 8
2441 10
我正在努力寻找在两个联赛中打球的球员
根据上表,我试图找到:
Player_id League_id_1 League_id_2
2441 8 10
提前致谢!
答案 0 :(得分:9)
看来你想在第一行中找到它。因此,您可以使用以下内容使用PIVOT
:
select player_id,
league_id_1,
league_id_2
from
(
select t1.player_id, t1.league_id,
row_number() over(partition by t1.player_id order by t1.league_id) rn
from table1 t1
inner join
(
select player_id
from table1
group by player_id
having count(distinct league_id) > 1
) t2
on t1.player_id = t2.player_id
) x
pivot
(
max(league_id)
for rn in (1 as league_id_1, 2 as league_id_2)
) p;
或者如果您无权访问PIVOT
函数,则可以使用带有聚合的CASE
语句:
select player_id,
max(case when rn = 1 then league_id end) league_id_1,
max(case when rn = 2 then league_id end) league_id_2
from
(
select t1.player_id, t1.league_id,
row_number() over(partition by t1.player_id order by t1.league_id) rn
from table1 t1
inner join
(
select player_id
from table1
group by player_id
having count(distinct league_id) > 1
) t2
on t1.player_id = t2.player_id
) x
group by player_id;
如果您不想将它放在一行中,那么您可以使用内部子查询:
select t1.player_id, t1.league_id
from table1 t1
inner join
(
select player_id
from table1
group by player_id
having count(distinct league_id) > 1
) t2
on t1.player_id = t2.player_id
答案 1 :(得分:1)
如果你不介意在行中使用它:
SELECT t.*
FROM myTable t
INNER JOIN
(
SELECT Player_id
FROM myTable
GROUP BY Player_id
HAVING COUNT(*) = (SELECT COUNT(DISTINCT(League_id)) FROM myTable)
) p ON t.Player_id = p.Player_id
这应该返回:
Player_id League_id 2441 8 2441 10
答案 2 :(得分:0)
如果您不能使用PIVOT(仅限11g),并且您希望在一行中输出所有League_id,请尝试以下操作:
DECLARE
v_owner VARCHAR2 ( 40 );
v_player_id VARCHAR2 ( 40 );
v_league_id VARCHAR2 ( 100 );
v_league_id_total VARCHAR2 ( 1000 );
/* First cursor */
CURSOR get_player_id
IS
SELECT DISTINCT player_id
FROM table1
ORDER BY player_id;
/* Second cursor */
CURSOR get_league_id
IS
SELECT league_id
FROM table1
WHERE player_id = v_player_id
ORDER BY league_id;
BEGIN
-- Open first cursor
OPEN get_player_id;
LOOP
FETCH get_player_id
INTO v_player_id;
v_league_id_total := '';
EXIT WHEN get_player_id%NOTFOUND;
-- Open 2nd cursor
OPEN get_league_id;
LOOP
FETCH get_league_id
INTO v_league_id;
EXIT WHEN get_league_id%NOTFOUND;
v_league_id_total := v_league_id_total || ' , ' || v_league_id;
END LOOP;
DBMS_OUTPUT.put_line ( RPAD ( v_player_id,
26,
' '
) ||
RPAD ( v_league_id_total,
26,
' '
) );
CLOSE get_league_id;
END LOOP;
CLOSE get_player_id;
EXCEPTION
WHEN OTHERS
THEN
raise_application_error ( -20001,
'An error was encountered - ' ||
SQLCODE ||
' -ERROR- ' ||
SQLERRM );
END;
输出将是这样的:
2139 , 8
2153 , 8
2303 , 8 , 10 (I added one more record.)
2441 , 8 , 10 , 11 , 12 (I added 2 more records)