Oracle 11g:如何将oracle表与自身结合起来?

use*_*987 3 sql oracle plsql oracle11g

我有一个表如下所示:

date          code                name    score         set
09/09/12     967873         Team A         24            1
09/09/12     967873         Team B         22            1
09/09/12     967873         Team A         21            2 
09/09/12     967873         Team B         16            2
02/04/12     965454         Team X         21            1
02/04/12     965454         Team Y         19            1
02/04/12     965454         Team X         21            2
02/04/12     965454         Team Y         19            2
Run Code Online (Sandbox Code Playgroud)

你猜对了!这是一场排球比赛!但是,我希望我的输出只能在一行中.例如:

date           code               Teams                 Set-1    Set-2     Set-3
09/09/12      967873             Team A VS.Team B       24-22    21-16       -
and so on.... 
Run Code Online (Sandbox Code Playgroud)

**Notice that the game could have a third set as well

我需要某种自联接来将上述格式细化为用户视图更容易的格式...如果您需要更多详细信息,请告诉我.

谢谢,

Cod*_*odo 7

查询可能如下所示:

with matches as (
   select "DATE", code, name,
      max(case when "SET" = 1 then score end) score_1,
      max(case when "SET" = 2 then score end) score_2,
      max(case when "SET" = 3 then score end) score_3,
      row_number() over(partition by "DATE", code order by name) team_no
    from games
    group by "DATE", code, name
)
select a."DATE", a.code, a.name || ' vs. ' || b.name teams,
  a.score_1 || '-' || b.score_1 set_1,
  a.score_2 || '-' || b.score_2 set_2,
  a.score_3 || '-' || b.score_3 set_3
from matches a
join matches b on a."DATE" = b."DATE" and a.code = b.code
where a.team_no = 1 and b.team_no = 2;
Run Code Online (Sandbox Code Playgroud)

日期集合是相当不幸的列名.

该查询分为3个步骤:

  1. 汇总记录以为每个团队创建一行并匹配.在该过程中,分数被分配给三个列set_1,set_2,set_3中的一个.
  2. 行号分配给每一行,每个匹配从1开始.结果是一个团队被分配1,另一个团队被分配2(列team_no).
  3. 结果表连接到自己,左侧是没有的团队.1和没有的球队的右侧.2使用匹配(日期和代码)作为连接条件.结果是每场比赛一行,两队的名称和分数.