data from 3 tables with later dates

Hello
Need help with the PL/SQL code, I need to write a code that will get the data from 3 tables with the most recent date.

For an individual ACT_CODE the output of the SQL query should display the data including the last dates back to 3 tables, if there is no
Date of the table, it should show the remaining data (think that the left join will do here)

Names of tables:
Institution_UPDT aiu
AC ASQ_CONTACT
GR_AUTHORIZE gr

All 3 tables have ACT_Code in common

Column names

INSTITUTION_UPDT IAU - IAU. ACT_CODE, AIU.project_id as proj, IAU. UPDT_TYPE_ID, IAU. User_id, IAU. UPDT_DATE

ASQ_CONTACT ac - ac. ACT_CODE as contact_code, ac.project_id, ac.first_name, ac.middle_initial, ac.last_
Name, AC.title, AC. Status, AC.status_date

GR_AUTHORIZE gr - GR ACT_CODE as grad_code, gr.name, gr.title AS grad_title, gr.submit_date


Are the names of the columns date
AC.status_date,
IAU. UPDT_DATE and
Gr.submit_date

Thanks to you all
appreciate your help

Jesh

Hi, Ngoumba,

If a given ACT_Code couldn't miss from any of the tables, then you will use better full outer joins, not a join left outer.

Perhaps it would be more effective to make a UNION of the three tables, then rotate the results in three datecolumns.

You can use the GROUP BY aggregation to get the last date for each ACT_Code in each table.
If you need other columns in the row which is the last date, you can use the ROW_NUMBER analytic function, like this:

SELECT  ACT_Code
,     updt_date
,     ROW_NUMBER () OVER ( PARTITION BY  ACT_Code
                          ORDER BY          updt_date     DESC
                  ) AS r_num
FROM    institution_updt

The lines with r_num = 1 are the most recent

This is a technique of ot the UNION-PIVOT example:

WITH     union_data     AS
(
     SELECT    ACT_Code
     ,       MAX (updt_date)     AS last_date
     ,       1                  AS table_id
     FROM       institution_updt
     GROUP BY  ACT_Code
UNION ALL
     SELECT    ACT_Code
     ,       MAX (status_date)     AS last_date
     ,       2                  AS table_id
     FROM       ASQ_Contact
     GROUP BY  ACT_Code
UNION ALL
     SELECT    ACT_Code
     ,       MAX (submit_date)     AS last_date
     ,       3                  AS table_id
     FROM       GR_Authorize
     GROUP BY  ACT_Code
)
SELECT       ACT_Code
,       MAX (CASE WHEN table_id = 1 THEN last_date END)     AS aiu_updt_date
,       MAX (CASE WHEN table_id = 2 THEN last_date END)     AS ac_status_date
,       MAX (CASE WHEN table_id = 3 THEN last_date END)     AS gr_submit_date
FROM       union_data
GROUP BY  ACT_Code
ORDER BY  ACT_Code
;

Published by: Frank Kulash, on September 16, 2009 15:02
Added UNION-pivot example

Tags: Database

Similar Questions

  • How to export data from the table with the colouring of cells according to value.

    Hi all

    I use jdeveloper 11.1.1.6

    I want to export data from the table with a lot of formatting. as for color cells based on value and so much. How to do this?

    You can find us apache POI-http://poi.apache.org/

    See this http://www.techartifact.com/blogs/2013/08/generate-excel-file-in-oracle-adf-using-apache-poi.html

  • expdp + query option to export from several tables with the same condition

    Hello

    We want to export a subset of data only from databases to another. Both on AIX.

    Source/testdatabase 11.2.0.3 (non partitioned tables)
    Target productiion 11.2.0.3 database (separate tables)

    Tables of same names of columns but diffrenet structures a partitioning index and traget so only want to import content

    Each source datbaase hascolumn seq number table and want only to extract the last months of data.


    TABLES:table1,table2...
    DUMPFILE=dump_dir
    CONTENT=data_only
    QUERY= table1:"WHERE seq_num >100 "
    want to use expdp but not sure how to make sure that all tables have the seq_num WHERE > 100 condition, if let table1: go out and have just
    QUERY = "WHERE seq_num > 100"this condition would apply to all tables that we want."


    I'm assuming that can also use impdp CONTENT = data_only?

    Any ideas/thoughts?

    Thank you

    QUERY = "WHERE seq_num > 100"this condition would apply to all tables that we want."

    Yes, it will work for all tables, but ensure that all exported table must include this column.

    QUERY
    Default: no
    Goal
    Allows you to filter the data that is exported by specifying a clause of a SQL SELECT statement, which is applied to all tables in the work of export or a specific table.

    The query_clause is usually a WHERE clause for the selection of refined lines, but could be any SQL clause. For example, an ORDER BY clause can be used to accelerate a migration from a table in a heap in a table held in index. * If a [schema]. table_name is not provided, the query is applied to (and must be valid for) all tables in the export job.*

    http://docs.Oracle.com/CD/B19306_01/server.102/b14215/dp_export.htm

  • How to match columns from two tables with

    Hello:
    I have two tables as below:

    Table1::(Base Table)
    Country | Prefix | Prefix_Length
    Travel | 001 | 3
    CountryB. 0012 | 4
    PaysC | 00443 | 5
    CountryD | 0091 | 4

    :(Detail Table) table2
    The population | Area | Prefix
    500 | AreaA | 0015921
    1000 | AreaB | 00122
    400. AreaC. 00443743
    300. ALIS | 0091333
    100. AreaA | 001

    I need to match these two tables with prefix columns (whose length is not fixed in the two tables: but it starts with 00 in the two tables). Two different countries the prefix may be similar up to a certain length. Thus, Prefix_Length can be used to determine (exactly) how much time should be taken in the search of Table2.

    Output:
    Country | Prefix | Area | Population
    Travel | 001 | AreaA | 600
    CountryB. 0012 | AreaB | 1000
    PaysC | 00443 | AreaC. 400
    CountryD | 0091 | ALIS | 300

    Please help me with your valuable comments.

    -Tender

    Try this

    with base_table as (
                        select 'CountryA' country,'001' prefix,3 prefix_length from dual union all
                        select 'CountryB','0012',4 from dual union all
                        select 'CountryC','00443',5 from dual union all
                        select 'CountryD','0091',4 from dual
                       ),
       detail_table as (
                        select 10 no_of_call,'0015921' prefix from dual union all
                        select 3,'00122' from dual union all
                        select 50,'00443743' from dual union all
                      select 50,'00443643' from dual union all
                        select 300,'0091333' from dual union all
                        select 60,'001' from dual
                       ) 
    
    SELECT  country,
            prefix,sum(no_of_call)
       FROM (
             select  country,
            b.prefix,no_of_call,
            decode(no_of_call,lead(no_of_call,1,0) over(partition by no_of_call order by b.prefix,no_of_call),'y','n') y_or_no
      from  base_table b,
            detail_table d
      where b.prefix = substr(d.prefix,1,prefix_length))
      where y_or_no !='y'
      group by  country,
            prefix
      order by country,
            prefix;
    

    Published by: Vi on 20 February 2012 01:07

  • How to read/select only the records from a table with non-English characters

    Hello
    I need to find all records in a table with non-English (mainly Chinese) characters in at least one of the varchar2 columns. Let me kow if someone knows a way by which it can be done using SQL/PLSQL.

    Best regards
    Imran
    select * from your table
    where your_column != convert(your_column, 'UTF8', 'US7ASCII)
    

    Replace UTF8 with your database character set

    Published by: thtsang on October 15, 2009 03:53 - unequal sign change of! =

  • Move from a table with htmldb_get

    Take a look at the following of the JS:
    ajaxRequest = new htmldb_Get(null,&APP_ID.,'APPLICATION_PROCESS=foo',0);
    arr = new Array();
    arr[0] = 'Lorem';
    arr[1] = 'Ipsum';
    ajaxRequest.addParam('x01', arr);
    alert(ajaxRequest.get());
    Is it possible to recover the arr in application process foo? I tried something like that, but it was not good:
    declare
      type arr is table of clob index by BINARY_INTEGER;
      clobArr arr;
    begin
      clobArr := wwv_flow.g_x01;
      htp.prn(clobArr(0));
    end;
    This returns the error below in the browser:
    sqlerrm:ORA-06550: line 5, column 23:
    PLS-00382: expression is of wrong type
    ORA-06550: line 5, column 3:
    PL/SQL: Statement ignored
    So a table with htmldb_get possible?

    Hello

    Just to know you can do it too

    JavaScript

    ajaxRequest = new htmldb_Get(null,&APP_ID.,'APPLICATION_PROCESS=FOO',0);
    arr = new Array();
    arr[0] = 'Lorem';
    arr[1] = 'Ipsum';
    for( var i=0,len=arr.length;i);}alert(ajaxRequest.get());
    
    
    And On Demand Process FOO
    
    htp.prn(apex_application.g_f01(2));
    
    Regards,
    Jari
    
    Edited by: jarola on Aug 25, 2010 11:39 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
    
  • How publish data from the table with some data loss all post in the forum

    I wonder how people are displayed the data in the table or the result of a query with losing them its format from Sqlplus display when they post in the forums of Oracle. I searched on the basis of knowledge of DB but I see no article about it. can you please help me or direct me to this link, I tried different options using code and other tags but nothing has worked, thank you for your help. Thank you.

    Edited by: Ariean October 3, 2011 12:34

    You can click on the link to the FAQ at the top right: http://wikis.sun.com/display/Forums/Forums+FAQ.

  • Delete data from a table with joins

    Hey guys,.

    IV struggled for a while with a sql now.
    I'm trying to remove some data from urole based on the www.lesormes.com in the select part.
    The selection is correct, but the part delete Deletes all data in the table urole and not only those found in the select.

    How can I delete all data by using a join?


    DELETE FROM urole
    WHEN THERE IS)
    SELECT *.
    User JOIN urole
    ON user.userid = urole.userid
    AND user.audit_version = urole.audit_version
    JOIN secrole
    ON urole.roleid = secrole.roleid
    WHERE user.audit_current = 'Y '.
    AND secrole.audit_current = 'Y '.
    AND IN secrole.rolename
    ('X',
    « Y »,
    « Z »,
    ));

    Thanks for your help in advance!

    Hello

    Welcome to the forum!

    Chances are, you don't want to join in the subquery EXISTS of EPM; It is more likely you want just like this correlated subqueries:

    DELETE FROM urole
    WHERE  EXISTS (
                      SELECT  0
               FROM    user
               WHERE   user.userid      = urole.userid
               AND     user.audit_version = urole.audit_version
               AND     user.audit_current = 'Y'
               )
    AND    EXISTS (
                      SELECT  0
               FROM    secrole
               WHERE   secrole.roleid         = urole.roleid
               AND     secrole.audit_current = 'Y'
               AND     secrole.rolename          IN ( 'X',
                                                        'Y',
                                          'Z'     -- No comma here
                                           )
               )
    ;
    

    or maybe an IN subquery:

    DELETE FROM urole
    WHERE   p_key  IN
                (
                SELECT  urole.p_key
                FROM    user
                JOIN    urole     ON     user.userid          = urole.userid
                                      AND     user.audit_version      = urole.audit_version
                JOIN    secrole     ON     urole.roleid           = secrole.roleid
                WHERE   user.audit_current     = 'Y'
                AND     secrole.audit_current     = 'Y'
                AND     secrole.rolename      IN ( 'X',
                                                     'Y',
                                       'Z'
                                     )
                )
    ;
    

    where p_key is a unique key (not necessarily a single column) of urole.

    It's just a guess; That's all I can do with the information you have posted. Test this carefully before to try it on your actual data.

    Whenever you have a problem, it allows to post a small example of data (CREATE TABLE and INSERT statements) and the results desired from these data.
    In the case of a DML (such as DEL) problem, the sample data must re - create the tables as they are to the DML, and the results will be the content of the modified table (urole) after the DML.

    Furthermore, there is a built-in function called user, the user is not a good name for a table.

  • Best way to generate a record per day from a table with the dates of the FEP/exp

    Hello

    A table equipped with various attributes and a date of eff and exp. for example Attributeto, 05/01/2012, 16/05/2012

    We want to create another table in this table for a record per day. for example 16 documents.

    What is the best way to achieve this in OWB?

    Thank you

    Assuming that you have a calendar table, then you can reach your rate table corresponding to the date table schedule between the table rates start date and end date.

    Something like:

    Select a.rate, rate_table b., calendar_table b.
    where b. between a.start_date and a.end_date

    should translate easily into a join of two tables in OWB?

    Concerning
    User909022

  • How to merge data from the table with a single line

    Hello

    I have three tables subscription_type, the address and the person. Here are the details of the table

    Person Subscription_type Address                                           

    Person_Id AdressType_id Address_id

    Person_name Description Address_type_id

    Person_id

    Address details


    There are three types of different address - home, postal and previous.

    Each person can have these three different addresses.

    I want to create a view that displays all addresses of three of each person in the table of the person in a single line.

    Any help please

    In your example, there are 2 rows of columns street1, TOWN, SUBURB etc for a single person. To convert this into a single line, with the new columns we could simply use CASES or DECODE in the select as the SQL below. To understand why consolidation function THAT MAX is used - remove the MAX and GROUP BY in SQL keyword and try.

    Select full_name

    , max (case when description = "Home" then end street1) Home_Street

    , max (case when description = "Home" then end suburb) home_suburb

    , max (case when description = end of the "Home" then City) home_city

    , max (case when description = "Home" then postal code end) home_postcode

    , max (case when description = "Home" then end state_name) home_state

    , max (case when description = 'Postal' then end street1) Postal_Street

    , max (case when description = 'Postal' and then end of suburb) Postal_suburb

    , max (case when description = 'Postal' then the city) Postal_city

    , max (case when description = 'Postal' and then end of CP) Postal_postcode

    , max (case when description = 'Postal' then state_name end) Postal_state

    , max (case when description = "Back" then end street1) Prev_Street

    , max (case when description = "Back" then end suburb) Prev_suburb

    , max (case when description = "Back" then city end) Prev_city

    , max (case when description = "Back" then postal code end) Prev_postcode

    address a

    S State

    No p

    Subscription_type att

    where a.person_id = p.person_id

    and a.state_id = s.state_id

    and a.address_type_id = att.address_type_id

    Full_name group

  • return Recordset from several tables with session variables

    First of all, let me start by appolgizing for the rawness of this question, but I'm really stuck...  I have two tables in a database, a table name, username, password and company (user logs on to a secure site using the UN and PW creating a session MM_username variable).  There are several users from different companies (IE 6 users of XYZ Corp., 20 ABC... etc.).  The second table has data that is specific to each company.  How to display the data in the second table so that it is specific to the user (ie: Robert of XYZ Corp. sees only specific data of XYZ Corp.)?

    Thank you very much

    What you would do, is to join the tables on the company name field in a query:

    SELECT * FROM tbl_name LEFT JOIN tbl1.company_name ON tbl2.company_name WHERE username = MM_username;

    If you need a more details or help database tables themselves you'll need post a few details anymore, but that's the gist of it.

    And just to add, is that if you try to add in the session.  Otherwise take your session for the company_name variable in table 1 and use it in a select query based on your session pages.

  • Removal of several tables with only loop FORALL

    I need to remove the data from several tables with unique FORALL. It seems that FORALL does not support. Please let me know the alternatives to achieve this goal.

    DB version: 11 GR 2

    Write switchis for all instructions, one for each deletion. There is no reason why it should not work.

    Compare:

    PLSQL 101 :

    Here are some things to know about FORALL:

    Each FORALL statement can contain only a single DML statement. If your loop contains two updates and a deletion, then you will need to write three statements FORALL

  • help in registration of the records from two tables

    HI: I have two tables joined the first field. The field is the primary key in the first table. Need help listing records from both tables with each a line/record results.
    create table EVENTS (
    event_key varchar2(64) primary key,
    event_description varchar2(64),
    create_time int
    );
    
    
    create table EVENT_UPDATES (
    event_key varchar2(64) NOT NULL ,
    update_description varchar2(64),
    update_time int
    );
    
    
    insert into EVENTS values('Event1', 'This is event1', 1);
    insert into EVENT_UPDATES values('Event1', 'Ticket created', 3);
    insert into EVENT_UPDATES values('Event1', 'Event cleared', 10);
    insert into EVENTS values('Event2', 'This is event2', 4);
    insert into EVENT_UPDATES values('Event2', 'Ticket created', 6);
    insert into EVENT_UPDATES values('Event2', 'Event cleared', 8);
    I want to print each record in the table of EVENTS such as a line and the corresponding records in EVENT_UPDATES as a line like this record
    Event1   1     This is event1
                3     Ticket created
                10   Event cleared
    Event2   4     This is event2
                6     Ticket created
                8     Event cleared
    TIA
    Ravi
    select  case weight
              when 1 then event_key
            end key,
            time_val,
            description
      from  (
              select  event_key,
                      create_time time_val,
                      event_description description,
                      1 weight
                from  events
             union all
              select  event_key,
                      update_time,
                      update_description,
                      2 weight
                from  event_updates
            )
      order by event_key,
               weight
    /
    
    KEY          TIME_VAL DESCRIPTION
    ---------- ---------- -------------------------
    Event1              1 This is event1
                        3 Ticket created
                       10 Event cleared
    Event2              4 This is event2
                        6 Ticket created
                        8 Event cleared
    
    6 rows selected.
    
    SQL> 
    

    SY.

  • Insert data from 3 tables of diff with some transpose logic

    Hi all

    I need to create a MS which will have three settings:

    Mast_report_id number, posted_on_date date, number of redord_id

    I have four tables which one is the destination and reset three source tables:

    The source tables:

    1 - mast_report

    create the table MAST_REPORT

    (

    MAST_REPORT_ID Number (38) not null,

    ANNUAL NUMBER (38),

    TITLE VARCHAR2 (500),

    STATUS VARCHAR2 (10),

    DATE OF POSTED_ON,

    NO_OF_PAGES NUMBER (8).

    BILLABLE_PAGES NUMBER (8).

    MAST_LANGUAGE VARCHAR2 (20).

    CONTRIBUTOR VARCHAR2 (80).

    CRAWL_DATE TIMESTAMP (6) default sysdate,.

    FILE_NAME VARCHAR2 (30),

    PAGE_PRICE NUMBER (10,2).

    DOC_PRICE NUMBER (10,2).

    CONTRIBUTOR_ID NUMBER (20)

    );

    2 - report_details:

    create the table REPORT_DETAILS

    (

    RECORD_ID Number (38) not null,

    DOC_ID Number not null, (38)

    ATTRIBUTE_TYPE VARCHAR2 (10),

    ATTRIBUTE_VALUE VARCHAR2 (200),

    REPORT_TYPE VARCHAR2 (100),

    ATTRIBUTE_ID VARCHAR2 (80)

    );

    3 - filters_for_docid:

    create the table FILTERS_FOR_DOCID

    (

    FILTER_ID Number not null, (38)

    CONTRIBUTOR VARCHAR2 (100),

    AUTHOR VARCHAR2 (100) default not null, "No. FILTERS".

    COUNTRY VARCHAR2 (100) default not null, "No. FILTERS".

    VARCHAR2 (100) region "No. FILTERS" not null default,

    COMPANY VARCHAR2 (100) default not null, "No. FILTERS".

    INDUSTRY VARCHAR2 (100) default not null, "No. FILTERS".

    VARCHAR2 (100) of the default OBJECT not null, "No. FILTERS".

    CREATED_DATE TIMESTAMP (6) SYSTIMESTAMP not null default,

    REPORT_TYPE VARCHAR2 (100) default not null, "No. FILTERS".

    NOM_FLUX VARCHAR2 (200),

    CHANNEL_ID NUMBER (8).

    NUMBER OF CU_ID

    );

    Destination table: filtered_document

    database version:

    BANNER
    1Oracle Database 11 g Release 11.2.0.1.0 - 64 bit Production
    2PL/SQL Release 11.2.0.1.0 - Production
    3CORE11.2.0.1.0Production
    4AMT for Linux: Version 11.2.0.1.0 - Production
    5NLSRTL Version 11.2.0.1.0 - Production

    As I menteioned above the user will pass three parameters: Mast_report_id, posted_on_date, redord_id

    Here, I need to take more condition (>) to the three parameters.

    For the extraction of data, the logic is below:

    Mast_report table has two columns mast_report_id and posted_on, we need to take a larger than the condition as:

    "Select * from mast_report where and mast_report_id > 7326280 and posted_on > 25 may 2015;

    It will show many recordings roughly 10,000 with all the columns including annual column, this annual column is card with doc report_details of the table

    Now report_details table, we need recover data with annual report_details = (all the table of mast_report annual that we extract our first query) and record_id > settings of this sp record id.

    lets assume he'll again get 10000 files with all the columns.

    Now the main logic is to extract the data of using our highest performance and the third table FILTERS_FOR_DOCID.

    Assume that this is the result of our query above:

    RECORD_IDANNUALATTRIBUTE_TYPEATTRIBUTE_VALUEREPORT_TYPEATTRIBUTE_ID
    17057411269222703COMPANYTGS NOPEC GEOPHYSICAL COMPANY ASASOCIETY REPORT100203621
    27112370469222704COMPANYVOLVO ABSOCIETY REPORT100062389
    37096287469222713COMPANYPARTNERRE LTD.SOCIETY REPORT100037448
    47056915069222713COMPANYPARTNERRE LTD.SOCIETY REPORT100037448
    57056788869222729COMPANYVITAMIN SHOPPE INC.SOCIETY REPORT108008193
    67038574869222749COMPANYABB LTD.SOCIETY REPORT100096991
    77096286569222756COMPANYMETTLER-TOLEDO INTERNATIONAL INC.SOCIETY REPORT100081108
    87056897869222756COMPANYMETTLER-TOLEDO INTERNATIONAL INC.SOCIETY REPORT100081108
    97038576169222777COMPANYSUNCOR ENERGY INC.SOCIETY REPORT100063497
    107056938969222784COMPANYSYMANTEC CORP.SOCIETY REPORT100043382
    117112676469222786COMPANYARROW ELECTRONICS INC.SOCIETY REPORT100084937

    here if using separate attribute_type of report_details, we have:

    Select distinct report_details attribute_type;

    ATTRIBUTE_TYPE
    1Object
    2INDUSTRY
    3COUNTRY
    4REGION
    5AUTHOR
    6COMPANY

    Here you can see over the structure of the third table table FILTERS_FOR_DOCID where above these distinct values of the second table are the columns of the third:

    And you can see the output of the query above to report_details table, including the attribute_type and attribute_type value.

    Here, we need to find in the third table with each attribute_type and values of his attribute_type_value with the topic of the third table columns, industry,... He values.

    as: consider attribute_type values 'COMPANY' and its "TGS NOPEC GEOPHYSICAL COMPANY ASA" attribute_value now we need to find

    in SOCIETY the third table cloumn with value "TGS NOPEC GEOPHYSICAL COMPANY ASA"... same for others...

    I must now go look for these lines of the third table which all combinations get matched, need us compare with like operator between the attribute_type column value and the value of the columns in the third diff table.


    Thanks in advance

    I have impleted above the requirement using pivot, CTE, and cases in where clause.

    Thanks for all the help

  • DB connectivity Kit: syntax error in a SELECTION of data from joined tables

    Hello everyone

    I'm putting in labview a SQL query on joined tables.

    As an example I take a database to store the data of basketball 2on2 matches, which tables are

    corresponds to (matchId, Thomas, teamB)

    teams (teamId,PlayerAname, PlayerBname, nationality)

    nationalities (NatId, natName)

    To get an array of result with the game as well as the names of player as well as their nationality, I use this query on MySQL (which works on command line interface)

    SELECT MatchID,
    T1. PlayerAName, t1. PlayerBName, n1.natName,
    T2. PlayerAName, t2. PlayerBName, n2.natName
    MATCHES m
    INNER JOIN teams t1 ON t1.teamID = m.teamA
    INNER JOIN teams t2 ON t2.teamID = m.teamB
    INNER JOIN nationalities L1 ON n1.natID = t1.nationality
    INNER JOIN nationalities n2 ON n2.natID = t2.nationality

    When I put it in labview, using the block 'select data', I get a syntax error as shown in the attached screenshot.

    Am I something mistanking using the JOIN examples statements or aliases?

    Thanks in advance!

    The select VI is designed to be a simple way to select from a table. I doubt that he can do joins (and would not certainly need the 'FROM', even if it can). What you can do instead calls the query execute VI and give him the complete SQL query. I don't remember if it returns the data in the recordset object, so you must do so separately.

Maybe you are looking for