Creating a view using multiple joins - by reducing the number of output lines

It is difficult to put into words exactly what I want to implement, so I'll just use an example. Let's say I have the following database:

game (id, time, place)

Reader (game_id, name)

Referee (game_id, name)

Foreign keys:
Player (game_id) references game (id)
Referee (game_id) references game (id)

It is a very special match, in which:
A game can have 1 to many players
A game can have from 1 to several arbitrators

I want to create the following view:

Game_overview (Game_id, time, player, referee)

It's easy to create this view with the following output:

Game1, 15:00, player1, Referee1
Game1, 15:00, player1, Referee2
Game1, 15:00, player2, Referee1
Game1, 15:00, player2, Referee2
Game1, 15:00, Joueur3, null
08:00, player1, Referee1, GaMe2
GaMe2, 08:00, player1, Referee2

HOWEVER, I want it to look like this:

Game1, 15:00, player1, Referee1
Game1, 15:00, player2, Referee2
Game1, 15:00, Joueur3, null
08:00, player1, Referee1, GaMe2
GaMe2, 08:00, null, Referee2

I think that this should not be TOO difficult to solve, but I can't really get my head around it.

Welcome to the forum!

Whenever you have a problem, please post CREATE TABLE and INSERT statements for your sample data. Sinve it's your first post, I'll do it for you:

CREATE TABLE     game
(       id          VARCHAR2 (10)     PRIMARY KEY
,     time          VARCHAR2 (10)
--,     location     VARCHAR2 (10)     -- No need to include columns that play no role in this problem
);

INSERT INTO game (id, time) VALUES ('Game 1',  '3PM');
INSERT INTO game (id, time) VALUES ('Game 2',  '8AM');

CREATE TABLE     player
(       game_id          VARCHAR2 (10)
,     name          VARCHAR2 (10)
);

INSERT INTO  player (game_id, name) VALUES ('Game 1',  'Player 1');
INSERT INTO  player (game_id, name) VALUES ('Game 1',  'Player 2');
INSERT INTO  player (game_id, name) VALUES ('Game 1',  'Player 3');
INSERT INTO  player (game_id, name) VALUES ('Game 2',  'Player 1');

CREATE TABLE     referee
(       game_id          VARCHAR2 (10)
,     name          VARCHAR2 (10)
);

INSERT INTO  referee (game_id, name) VALUES ('Game 1',  'Referee 1');
INSERT INTO  referee (game_id, name) VALUES ('Game 1',  'Referee 2');
INSERT INTO  referee (game_id, name) VALUES ('Game 2',  'Referee 1');
INSERT INTO  referee (game_id, name) VALUES ('Game 2',  'Referee 2');

In this way, people who want to help you can recreate the problem and test their ideas.

In addition, to say what version of Oracle you are using. The following query will work in Oracle 9.1 or more.

What you asked is what I call a Query, fixed-price , and this is a way to do it:

WITH     player_plus     AS
(
     SELECT     game_id
     ,     name
     ,     ROW_NUMBER () OVER ( PARTITION BY  game_id
                               ORDER BY          name
                       )         AS r_num
     FROM    player
)
,     referee_plus     AS
(
     SELECT     game_id
     ,     name
     ,     ROW_NUMBER () OVER ( PARTITION BY  game_id
                               ORDER BY          name
                       )         AS r_num
     FROM    referee
)
SELECT       g.id
,       g.time
,       p.name     AS player_name
,       r.name     AS referee_name
FROM             player_plus     p
FULL OUTER JOIN  referee_plus   r  ON   p.game_id     = r.game_id
                                AND     p.r_num          = r.r_num
JOIN           game          g  ON     g.id          = COALESCE (p.game_id, r.game_id)
ORDER BY  g.id
,         COALESCE (p.r_num, r.r_num)
;

Output:

ID         TIME       PLAYER_NAM REFEREE_NA
---------- ---------- ---------- ----------
Game 1     3PM        Player 1   Referee 1
Game 1     3PM        Player 2   Referee 2
Game 1     3PM        Player 3
Game 2     8AM        Player 1   Referee 1
Game 2     8AM                   Referee 2

I see that you have more arbitrators than players in a game. If such was not the case, then you might make it a bit more efficient using a LEFT OUTER JOIN between p and r, rather than a FULL OUTER JOIN, and you can also use only the columns of p where I use COALESCE.

Published by: Frank Kulash, March 9, 2012 18:15
Fixed spelling

Tags: Database

Similar Questions

  • Create a view using the table

    Hi all

    I am beginner in Oracle.

    I have a two-column table that I use to create a view documents/statement once it meets the qualification.

    The table has fields. 1 number and 2. Group. If there is more than 3 records found on this table with the same NUMBER and the GROUP he should create this table view.

    Thank you

    Pramod Devkate

    The training is therefore two lines for a ticket and the agent. When the third row is added, create a line in the summary table. Later a fourth line is added to the table of training for this ticket and the agent, but we do not update the line in the summary table. We only touch the summary table when the third row is added to the training table, then it is only updated by the application. Very well

    INSERT INTO summary (ticket, agent, total_travel, total_mtts)

    Select ticket agent, sum (travel), sum (mtts)

    training

    where (ticket, agent) not in

    (select the ticket agent summary)

    Group ticket, agent

    having count (*) > 2.

    This inserts in the table only notes and agent ID that do not exist already.

  • I do my job to the computer on a MAC computer. I want to create a document using Pages and then convert the document to PDF and send a group email. I want to send the PDF using the pdf for each receiver icon must click the icon to open t

    I do my job to the computer on a MAC book PRO. I want to create a document using Pages and then convert the document to PDF and send a group email. I want to send the PDF using the pdf for each receiver icon must click the icon to open the document. My problem is the document does not show the icon, but rather the document is already open. I spoke with 2 Apple. 'Experts' care and can help me. Can someone tell me what to do?

    It's a question of how the recipients e-mail programs deal with attachments. Many e-mail programs will open all the files they can handle, including files jpg and PDF, by default, and if the recipient has not changed that there is nothing you can do about it. The only solution is to the compress first, then it will be delivered as an attachment, allowing the recipient to decompress and open it.

  • You can create an application using Adobe DPS, then go the Folio to a programmer to add interactivity?

    I would like to know if I can create an application using Adobe DPS, Col. of the folio to a programmer to add advanced interactivity which does not DPS. I would like to the programmer to use XCode or Android SDK because it is a standard, but they can also use c#, JavaScript and many other coding languages. Folio would serve the purpose of a waterproof digital mock-up for the programmer.

    DPS is very extensible using HTML, but the folios can be cracked open

    to add to.

  • How to reduce the number, do not round

    Hi all
    I want to reduce the number for the 2nd symbol. For example, if we have the real value - 100.556 I want to show 100,55. I tried with the format as a mask:
    select  to_char(100.555,'FM999G999G999G999G990D00') number from dual;
    result:
    100.56
    expected result:
    100.55
    .


    Any ideas?
    Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - Production
    PL/SQL Release 11.1.0.7.0 - Production
    "CORE     11.1.0.7.0     Production"
    TNS for Linux: Version 11.1.0.7.0 - Production
    NLSRTL Version 11.1.0.7.0 - Production
    Thanks in advance,
    Bahchevanov.

    Use the TRUNK:

    select  trunc(100.555, 2) from dual;
    
  • Reduce the number of div tags

    What I could do to reduce the number of div tags used on this page?

    http://www.lash-it.com/what/kayakexamples/kayakexamples.html

    Why do you have comment float: left;?

    .examples_row img {}

    / * [disabled] float: left; */

    }

    Try this:

    {.examples_row}

    height: 300px;

    Width: 880px;

    }

    .examples_row img {}

    float: left;

    }

    .examples_row h1 {}

    do-size: 12px;

    text-align: justify;

    top of the margin: 50px;

    margin left: 260px;

    }

    .examples_row p {}

    margin left: 260px;

    }

  • Is it good to keep my macbook on charge all the time? This reduces the number of cycles of battery I would have otherwise?

    I have a 2015 13-inch macbook pro Retina display. What is the best way to keep the battery in good conditions? In particular: When should I charge it? Only when the power is low)<20%) or="" anytime="" that="" i="" can?="" more="" in="" particular:="" if="" i="" keep="" it="" in="" charge="" all="" the="" time,="" will="" this="" be="" good="" or="" bad="" for="" the="" battery?="" will="" it="" reduce="" the="" number="" of="" battery="" cycles="" that="" i="" would="" otherwise="" have?="" many="">

    Keep the computer plugged in whenever possible.

    If you keep the computer always connected, make sure that at least twice a month

    Run it on battery until battery charge level falls to about 40-50%.

    Please don't completely discharge the battery. Discharge the battery completely will reduce wear and tear on the battery.

    Trying to keep the number of Cycles of battery low does ' t help.

    For more information:

    Section: To optimize the battery life

    http://support.Apple.com/en-us/HT204054

    Best.

  • Reduce the number of ticks on a xy plot

    Hi all

    I have a chart that looks very busy on the x axis.

    Anyone know a way to reduce the number of ticks that only, say 5, are visible?

    Thank you

    Sean

    Like this for example

  • Zoom in French - to the acrobat reader do not reduce the number of words per line to fit screen

    Zoom in French - to the acrobat reader do not reduce the number of words per line to fit as screen micorsoft Word knows to extend this feature is the free acrobat reader - or only exist in a paid product Adobe - and how is - this product called from adobe on its less expensive way for Windows 10 .it.

    You don't ask to convert to word. You seemed to ask if you could zoom in on a pdf document and have the text reformatting "As Microsoft Word can do". The answer is higher. Drive abyy fine will not redistribute the text either. Is neither Adobe Acrobat

    But you touched kind on your answer. With ExportPDF or Adobe Acrobat, you can convert the PDF file to a Word document that will be redistributed as you want. But this is not a pdf file. It will be a Word document.

  • VM is to have 1 CPU, can we reduce the number of core for CPU.

    VM is to have 1 CPU, can we reduce the number of core for CPU.


    Capture.JPG

    In this article: the number of cores per processor in a virtual machine (1010184)

  • reduce the number of columns in the case query

    Hi all

    I'm running on 10 G R/2.

    I have a query that produces columns with the number of steps.

    SUM (CASE WHEN LTRIM (RTRIM (W_O)) = 'ROKOLBIN' THEN 1 ELSE 0 END) AS "O_ROKOLBIN."
    SUM (CASE WHEN LTRIM (RTRIM (W_I)) = 'ROKOLBIN' THEN 0 OTHERWISE 1 END) AS "I_ROKOLBIN."
    sum (case when LTRIM (RTRIM (W_O)) = "SYLVAIN", then 1 else 0 end) as "O_GULURU."
    sum (case when LTRIM (RTRIM (W_I)) = "SYLVAIN", then 1 else 0 end) as "I_GULURU."
    sum (case when LTRIM (RTRIM (W_ON)) = 'PURE' then 1 else 0 end) as "O_PURE."

    I want to reduce the number of columns to 2,

    A column is for Division.Division can be O_ROKOLBIN, I_ROKOLBIN, O_GULURU, I_GULURU, O_PURE
    The other column is Subtotal.Subtotal are the sums as above, SUM (CASE WHEN LTRIM (RTRIM (W_O)) = "ROKOLBIN", 1.)

    Can anyone advie how I acheiev it.

    Thank you.

    Hello

    CrackerJack wrote:
    ... Data are from Jan 12 to today, 1 million + records, that's why I'm unable to provide comprehensive data and simply copied an example of data.

    Nobody wants you to post 1 million rows. 10 lines can be many. Just examples of data make sure that validation really produces the results you post.
    >

    I copied data from 16 Jan just differentiate different dates.

    I also tried trunc, but who has still not the sum of each divisions.

    Highlight a few places where the query I posted produces erroneous results and explain how to get good results in these places. Give concrete examples showing how to get the correct results of the sample data.

  • Creating a view using causes error ORA-00600

    Hello ladies and gentlemen,

    I tried to deploy a recursive query, as a point of view in Oracle XE and Standard Edition, nor a lot of success.

    The query is in this issue here: http://stackoverflow.com/questions/17358109/how-to-retrieve-all-recursive-children-of-parent-row-in-oracle-sq

    with recursion_view(base, parent_id, child_id, qty) as (
       -- first step, get rows to start with
       select 
      parent_id base, 
      parent_id, 
      child_id, 
      qty
      from 
      md_boms
    
      union all
    
      -- subsequent steps
      select
       -- retain base value from previous level
      previous_level.base,
       -- get information from current level
      current_level.parent_id,
      current_level.child_id,
       -- accumulate sum 
       (previous_level.qty + current_level.qty) as qty 
      from
      recursion_view previous_level,
      md_boms current_level
      where
      current_level.parent_id = previous_level.child_id
    
    )
    select 
      base, parent_id, child_id, qty
    from 
      recursion_view
    order by 
      base, parent_id, child_id

    The query itself works and returns the results. However, when I try to create a view with this query, I get errors.

    I posted two screenshots: http://www.williverstravels.com/JDev/Forums/StackOverflow/17358109/ViewError.jpg and http://www.williverstravels.com/JDev/Forums/StackOverflow/17358109/InternalError.jpg one with the! and * is when I am using JDeveloper 11g, using the navigation database, right-click on the view and select "New View". I get the error when I click on OK. I can indeed create the view through a sql script, but when I try to view the data, I get the error ORA_00600.

    I tried it work on my machine the two premises for XE (version 11.2.0.2.0) and 11g Standard Edition (11.2.0.2.v6) via Amazon Web Services. The result is the same.

    Does anyone know how to get around this problem?

    Not 5 minutes after I have this post, I decide not to use the graphical editor of JDev and simply write

    SELECT * FROM BOMS_VIEW;

    And it works like a charm.  I can not just use data tab to display records in the editor.  Wish I'd known that there is 5 hours.

  • Cannot create Materialized View using the PL/SQL procedure

    Hello

    I have a question related to the creation of materialized view.
    I have a stored procedure that creates the materialized view. When you try to perform this procedure, I get not enough privileges error: ORA-01031.

    When I run the content of this procedure as a PL/SQL block anonymous their materialized view is created without any complications.
    Can you please advice me on this subject?
    It is even possible to create a materialized view in the stored procedure as I found no info on this subject.

    Thank you
    Petr

    Hi chudapet,

    Whenever you make in procedure, you must have direct subsidies and not through a role.

    Most likely the grant to create a materialized view is available via a role to your username.
    Assign a direct grant to the user:

    grant create materialized view to scott;
    {code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
    
  • Can we average channel error using multiple channels to measure the same voltage?

    I don't know how correlated error terms are between measuring channels max, but it occurred to me that, if they were relatively independent, I might be able to sample the signal even with several channels and increase accuracy.

    For example, rather than measure a voltage with an AI only at 100 kHz, I could connect up to 10 different lines to HAVE the signal, sample to 10 kHz on each line.  This should allow to reach me on average some of the error associated with each channel (, or so I think).

    Can someone speak definitively to this?

    Thank you

    Sean

    Well, if you are using a MULTIPLEXED Board (everything is not specced for simultaneous sampling) then each channel is connected to the ADC even one after the other, best that you would be able to do is extremely, extremely small variations into the paths of each channel of the multiplexer.  This would still be massively overshadowed by the inherent noise from the system and the accuracy of the device.

    Your best bets to reduce the measurement error is to oversample in one way to reduce the effects of noise and to calibrate the unit before starting each test to keep variations of temperature.  In addition, make sure you keep your calibrated Board (most of the boards have a calibration 1 year of the cycle).

    For some applications, you should also consult wiring field and considerations of noise for analog signals, How to eliminate ghosting of my measurements? and Troubleshooting unexpected tensions, floating or crosstalk on Analog Input Channels to better account for ghosting and the issues of the hour.

  • You can use multiple computers to change the project of the elements of the first?

    I use first Elements 10.  I built a new project on my desktop, because the Office has a firewire port to capture video from my camcorder and my laptop is not a firewire port.  The project is stored on my home network.  I seem to be able to do editing very well using the desktop computer that the project has been created, but it will not directly charge on the cell for editing.  Premiere Elements is configured the same on both computers.  I guess my question is - Premiere Elements stores something on the computer on which the project was created on not stored on the network drive?    How can I fix the problem so that I can edit on my laptop? The laptop is a high-end Dell XPS with an i7 processor that I use for other projects of creation, so the capacity of portable computers is not a problem.

    Thank you

    Bill

    If I have a very fast NAS and the network, I found that to effectively edit a project, I want my project, and active at least an external FW 800 (same drive letter of the operating system on each computer) and an eSATA would be even better.

    I do all the time and my transportation projects between my laptop by the pool and work stations in the editing room.

    I've set up each project, with all assets (or Copies, as most of my goods are stored on the NAS), in a hierarchy of files for this project. With the drive letter set the same on every machine I migrate seamlessly and with zero problems. Mega-projects, with 1, in thousands of dollars in assets, loading quickly - unlike when working on the network, or of the SIN.

    But with a little planning, you should have zero problem.

    Good luck

    Hunt

Maybe you are looking for