看来您希望在第一行中使用它。因此,您可以使用以下命令将其放在一行中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;
请参阅带有演示的 SQL Fiddle
或者,如果您无权访问该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;
请参阅带有演示的 SQL Fiddle
如果您不希望它在一行中,那么您可以使用内部子查询:
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
请参阅带有演示的 SQL Fiddle