如何在 Oracle 中使用 SQL 查询获取以下输出
设想:
假设在名为 Team 的表中包含 4 条记录,我们需要安排每支球队与对方球队之间的比赛:
Team
----
India
Pakistan
Srilanka
Australia
Output :
----
India VS Pakistan
India VS Srilanka
India VS Australia
Pakistan VS Srilanka
Pakistan VS Australia
Srilanka VS Australia
Run Code Online (Sandbox Code Playgroud)
您可以在同一个表之间使用完整联接,其中 a.team <> b.team
select
a.team_name || 'VS' || b.team_name
from
table_team a,
table_team b
where
a.team_id < b.team_id ;
Run Code Online (Sandbox Code Playgroud)
如果我们考虑 <> 那么就会有重复,例如。Ind vs Pak 和 Pak vs Ind。因此字符串比较较少,始终会选择组合
您可以使用简单的join. . . 但不是cross join:
with teams as (
select 'India' as team FROM dual UNION ALL
select 'Pakistan' as team FROM dual UNION ALL
select 'Srilanka' as team FROM dual UNION ALL
select 'Australia' as team FROM dual UNION ALL
)
select t1.team as team1, team2.team team2
from teams t1 join
teams t2
on t1.name < t2.name;
Run Code Online (Sandbox Code Playgroud)
这将为每一对生成一行。
如果您确实想保持排序以便获得与您指定的对完全相同的输出,则需要一个排序列:
with teams as (
select 'India' as team, 1 as n FROM dual UNION ALL
select 'Pakistan' as team, 2 FROM dual UNION ALL
select 'Srilanka' as team, 3 FROM dual UNION ALL
select 'Australia' as team, 4 FROM dual UNION ALL
)
select t1.team as team1, team2.team team2
from teams t1 join
teams t2
on t1.n < t2.n;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7911 次 |
| 最近记录: |