Join same table 3 times, count from two other tables

Hi all!
I have 3 tables
RECORDS
Id, Record_Id
ITEMS
Id, Record_Id
ARTICLES
Id, Record_Id
I need to join RECORDS table 3 times R1,R2,R3 and get count of items R2 and R3 have and count articles that R3 has.
R2 must have ITEMS and R3 must have items, R3 may have articles. R1 may have multiple children and R2 may have multiple children.
Solution I'm using is following, but distinct makes it slow...
select r1 as ParentRecordId,count(distinct i1) as Volumes,count(distinct i2) as Numbers, count(distinct a1) as Articles
from
    select r1.id as r1,i1.id as i1,i2.id as i2,a.id as a1
    from records r1 inner join records r2 on r1.id=r2.record_id
    inner join records r3 on r2.id=r3.record_id
    inner join items i1 on r2.id=i1.record_id
    inner join items i2 on r3.id=i2.record_id
    left join articles a on a.record_id=r3.id
) as sel
group by r1
order by 1
Regards
Meelis

Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect. 
This is minimal polite behavior on SQL forums. And thanks for no sample, too! 
>> I have 3 tables <<
No, you have three identical decks of 1950's punch cards written in bad SQL. 
There is no such thing as a generic, universal “id” in RDBMS. It has to be the identifier of something particular. 
Magical columns appear in your query. 
There is no such concept as “child' and “parent” in RDBMS. That was network and hierarchical databases. We have referenced and referencing tables. 
We do not use column positions in the ORDER BY cause; any change in the query used in the cursor will screw up everything. 
Would you like to try again? 
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL

Similar Messages

  • Calculating count from two fact tables

    Hi Guys,
    My requirement,
    i have two fact table F1, F2 connected with a D1 dimension table, all table connected with a id column
    F1 ---------D1------------F2
    n 1 1 n
    i want to find out the distinct count from Fact F1 where the value also present in F2( ie. F1.id= F2.id condition).
    this measure usefull through out my project so i want create a logical column, how to create it.
    I tried this way:
    i Created two fact table in to one fact table by adding logical source, and created a logical column from existing logical source where F1.id=D1.id and D1.id=F2.Id but it is wrong
    Can any suggestion for solve my problem.
    Thanks in advance!!!

    Hi,
    You can create an opaque view in physical layer and wrire a sql like
    Select f1.id,count(*) from f1,f2 where f1.id=f2.id group by f1.id.Join this through id with dimesnion and add this fact table in LTS of your fact and use count(*) in report.
    Regards,
    Sandeep

  • Update joining two other tables.

    Hi,
    I have a question on update of one table using two other tables.
    There are three tables: a_visitors(vis_str, vis_flag), b_hub(vis_str ), c_uv_xref(vis_str, user_str).
    And a_visitors.vis_flag needs to be updated with '1', '2' or '3'.
    1 - if there is a record in b_hub table exists where a_visitors.vis_str = b_hub.vis_str
    and a_visitors.vis_str = c_c_uv_xref.vis_str and c_uv_xref.user_str like *'%type_1%'*
    2 - if exists where a_visitors.vis_str = b_hub.vis_str
    and a_visitors.vis_str = c_c_uv_xref.vis_str and c_uv_xref.user_str like *'%type_2%'*
    3- if exists where a_visitors.vis_str = b_hub.vis_str
    Thanks a lot for your help !!!
    And here's the code
    CREATE TABLE "A_VISITORS"
        "VIS_STR"  VARCHAR2(20 BYTE),
        "VIS_FLAG" VARCHAR2(20 BYTE)
    REM INSERTING into A_VISITORS
    Insert into A_VISITORS (VIS_STR,VIS_FLAG) values ('aaa',null);
    Insert into A_VISITORS (VIS_STR,VIS_FLAG) values ('bbb',null);
    Insert into A_VISITORS (VIS_STR,VIS_FLAG) values ('ccc',null);
    Insert into A_VISITORS (VIS_STR,VIS_FLAG) values ('ddd',null);
    Insert into A_VISITORS (VIS_STR,VIS_FLAG) values ('eee',null);
    CREATE TABLE "B_HUB"  ("VIS_STR" VARCHAR2(20 BYTE)   );
    REM INSERTING into B_HUB
    Insert into B_HUB (VIS_STR) values ('aaa');
    Insert into B_HUB (VIS_STR) values ('bbb');
    Insert into B_HUB (VIS_STR) values ('fff');
    Insert into B_HUB (VIS_STR) values ('ggg');
    Insert into B_HUB (VIS_STR) values ('hhh');
    CREATE TABLE "CARAW"."C_UV_XREF" (
        "VIS_STR"  VARCHAR2(20 BYTE),
        "USER_STR" VARCHAR2(20 BYTE)
    REM INSERTING into C_UV_XREF
    Insert into C_UV_XREF (VIS_STR,USER_STR) values ('aaa','type_1');
    Insert into C_UV_XREF (VIS_STR,USER_STR) values ('aaa','aaaaa');
    Insert into C_UV_XREF (VIS_STR,USER_STR) values ('bbb','type_2');
    Insert into C_UV_XREF (VIS_STR,USER_STR) values ('ccc','ttt');
    Insert into C_UV_XREF (VIS_STR,USER_STR) values ('ddd',null);
    Insert into C_UV_XREF (VIS_STR,USER_STR) values ('eee','kkk');
    Insert into C_UV_XREF (VIS_STR,USER_STR) values ('fff','lll');
    Insert into C_UV_XREF (VIS_STR,USER_STR) values ('ggg','aaaaa');
    Insert into C_UV_XREF (VIS_STR,USER_STR) values ('hhh','aaaaa');
    Insert into C_UV_XREF (VIS_STR,USER_STR) values ('aaa','type_2');Edited by: lsy_nn on Sep 20, 2010 12:06 PM
    Edited by: lsy_nn on Sep 20, 2010 12:07 PM

    Hi,
    Thanks for posting the sample data.
    Don't forget to post the results you want from that data (that is, the contents of a_visitors after the UPDATE.)
    Here's one way:
    MERGE INTO     a_visitors     a
    USING  (
            SELECT    NVL (b.vis_str, c.vis_str)     AS vis_str
            ,          COUNT (CASE WHEN c.user_str LIKE '%type_1%' THEN 1 END)     AS type_1_cnt
            ,          COUNT (CASE WHEN c.user_str LIKE '%type_2%' THEN 1 END)     AS type_2_cnt
            FROM                 b_hub     b
            FULL OUTER JOIN  c_uv_xref     c     ON     b.vis_str     = c.vis_str
            GROUP BY  NVL (b.vis_str, c.vis_str)
           )                          bc
    ON     (a.vis_str            = bc.vis_str)
    WHEN MATCHED THEN
    UPDATE  SET  a.vis_flag     = CASE
                        WHEN  bc.type_1_cnt > 0  THEN  '1'
                        WHEN  bc.type_2_cnt > 0  THEN  '2'
                                                    ELSE  '3'
                          END
    ;

  • Get the Common from Two Internal Tables with same structure

    Hi ,
    I need to get the Common data from Two Internal Tables with same structure with using the looping method.
    For e.g.
    I have two internal table say ITAB1 and ITAB2.
    ITAB1 has values A,B,C,D,E,F
    ITAB2 has values A,H,B,Y,O
    Output at runtime should be : A,B

    Hi mohit,
    1. If u want to compare all fields,
       for matching purpose,
       then we can do like this.
    2.
    report abc.
    data : a like t001 occurs 0 with header line.
    data : b like t001 occurs 0 with header line.
    loop at a.
      LOOP AT B.
        IF A = B.
          WRITE :/ 'SAME'.
        ENDIF.
      endloop.
    ENDLOOP.
    regards,
    amit m.

  • Getting DISTINCT count from two different columns

    Hi all,
    I have following query which gives currency code from two different tables. I would like to get the distinct count of currency codes from these two different columns.
    SELECT eb.person_seq_id, eb.bonus_amount, eb.currency_cd, ed.currency_cd_host
    FROM fr_emp_bonuses eb, fr_emp_details ed, fr_periods p
    WHERE eb.person_seq_id = ed.person_seq_id AND ed.period_seq_id = eb.period_seq_id
    AND ed.period_seq_id = p.period_seq_id AND p.period_status = 'CURRENT'
    AND eb.bonus_amount >= 0 AND eb.person_seq_id = 3525125;
    This query gives following result
    3525125     240000     USD     INR
    3525125     0      USD     INR
    3525125     60000      USD     INR
    3525125     50000      USD     INR
    There are two distinct currency codes (USD, INR) and total amount is 350000. So I am looking for a query to give me the following result
    3525125     350000 2
    Thanks in advance

    Hi,
    Here's one way:
    WITH     original_query     AS
         SELECT  eb.person_seq_id
         ,     eb.bonus_amount
         ,     eb.currency_cd
         ,     ed.currency_cd_host
         FROM     fr_emp_bonuses         eb
         ,     fr_emp_details          ed
         ,     fr_periods          p
         WHERE      eb.person_seq_id    = ed.person_seq_id
         AND      ed.period_seq_id    = eb.period_seq_id
         AND      ed.period_seq_id    = p.period_seq_id
         AND      p.period_status         = 'CURRENT'
         AND      eb.bonus_amount     >= 0
         AND     eb.person_seq_id    = 3525125
    ,     unpivoted_data     AS
         SELECT     person_seq_id
         ,     bonus_amount
         ,     currency_cd
         FROM     original_query
        UNION ALL
            SELECT  person_seq_id
         ,     0               AS bonus_amount
         ,     currency_cd_host     AS currency_cd
         FROM     original_query
    SELECT       person_seq_id
    ,       SUM (bonus_amount)          AS total_bonus_amount
    ,       COUNT (DISTINCT currency_cd)     AS distinct_currency_cds
    FROM       unpivoted_data
    GROUP BY  person_seq_id
    ;There may be a shorter, more efficient way to get the same results, but without knowing more about your tables, I can't tell.
    The tricky thing is getting two columns (currency_cd and currencuy_cd_host in this case) counted together. You can't simply say
    COUNT (DISTINCT eb.currency_cd) +
    COUNT (DISTINCT ed.currency_code_host)That happens to get the correct result with the sample data you posted, but what if you had data like thEe following?
    currency_cd     currency_cd_host
    INR          USD
    USD          INRHere, the count of distinct currency_cds is 2, and the count of distinct currency_cd_hsots is also 2. Does that mean the grand total is 2 + 2 = 4? No, the 2 codes in one column arte the same 2 codes as in the other column. We need to get both currency_cd and currency_cd_hsot into the same column, and then do COUNT (DISTINCT ...) on that combined column. A UNION, as shown above, will certainly do that, starting with your query as you posted it. The query you posted isn't necessarily the best frist step towards this result, however, so there may be a much better approach, depending on your tables.
    Edited by: Frank Kulash on Feb 1, 2012 6:21 PM
    Here's a slightly shorter, and probably more efficient way to get the same results:
    WITH     cntr     AS
         SELECT     LEVEL     AS n
         FROM     dual
         CONNECT BY     LEVEL     <= 2
    SELECT       eb.person_seq_id
    ,       SUM (eb.bonus_amount)          AS total-amount
    ,       COUNT ( DISTINCT CASE
                        WHEN  c.n = 1
                        THEN  eb.currency_cd
                        ELSE  ed.currency_cd_host
                      END
              )               AS distinct_currency_cds
    FROM       fr_emp_bonuses    eb
    ,       fr_emp_details    ed
    ,       fr_periods          p
    ,       cntr              c
    WHERE        eb.person_seq_id  = ed.person_seq_id
    AND        ed.period_seq_id  = eb.period_seq_id
    AND        ed.period_seq_id  = p.period_seq_id
    AND        p.period_status   = 'CURRENT'
    AND        eb.bonus_amount   >= 0
    AND       eb.person_seq_i   = 3525125
    --       NOTE: no join condition involving c; we really do want a cross-join
    GROUP BY  eb.person_seq_id
    ;

  • Sum two different columns from two different tables

    Can you select and sum two different columns, from two different tables in the same sql statement?
    i.e.
    table1
    Item----OnHand_Qty
    A--------10
    A--------15
    B--------10
    B--------10
    C--------20
    table2
    Item----Trx_Qty
    A--------2
    A--------4
    A--------6
    B--------1
    B--------1
    C--------4
    I'm looking for the following results from a query
    Item----Sum(Onhand_Qty)---Sum(Trx_Qty)
    A--------25

    Like this?
    SQL> create table table1 (item,onhand_qty)
      2  as
      3  select 'A', 10 from dual union all
      4  select 'A', 15 from dual union all
      5  select 'B', 10 from dual union all
      6  select 'B', 10 from dual union all
      7  select 'C', 20 from dual union all
      8  select 'D', 30 from dual
      9  /
    Tabel is aangemaakt.
    SQL> create table table2 (item, trx_qty)
      2  as
      3  select 'A', 2 from dual union all
      4  select 'A', 4 from dual union all
      5  select 'A', 6 from dual union all
      6  select 'B', 1 from dual union all
      7  select 'B', 1 from dual union all
      8  select 'C', 4 from dual union all
      9  select 'E', 3 from dual
    10  /
    Tabel is aangemaakt.
    SQL> select nvl(t1.item,t2.item) item
      2       , t1.sum_onhand_qty
      3       , t2.sum_trx_qty
      4    from ( select item, sum(onhand_qty) sum_onhand_qty
      5             from table1
      6            group by item
      7         ) t1
      8         full outer join
      9         ( select item, sum(trx_qty) sum_trx_qty
    10             from table2
    11            group by item
    12         ) t2
    13         on (t1.item = t2.item)
    14  /
    I SUM_ONHAND_QTY SUM_TRX_QTY
    A             25          12
    B             20           2
    C             20           4
    E                          3
    D             30
    5 rijen zijn geselecteerd.Regards,
    Rob.

  • How to create a foreign key for the table from two different tables?

    Hi All,
    I have a three table like below. In the below table SAMPLE_CONS_CHECK and SAMPLE_CONS2_CHECK will be having the primary key for NAME column. The same SAMPLE_CONS3_CHECK table also having the primary key for NAME column and forieign key for SAMPLE_CONS_CHECK and SAMPLE_CONS2_CHECK tables. See the below code 2
    code 1:
    CREATE TABLE SAMPLE_CONS_CHECK
            (NAME VARCHAR2(10),
            SERIES  VARCHAR2(5)
    CREATE TABLE SAMPLE_CONS2_CHECK
            (NAME  VARCHAR2(5),
             MODEL  NUMBER
    CREATE TABLE SAMPLE_CONS3_CHECK
            (NAME  VARCHAR2(5),
             MODEL_NO  NUMBER
            )code 2
    alter table SAMPLE_CONS_CHECK
    add constraint SAMPLE_CONS_CHECK_pk primary key (NAME)
    alter table SAMPLE_CONS2_CHECK
    add constraint SAMPLE_CONS2_CHECK_pk primary key (NAME)
    alter table SAMPLE_CONS3_CHECK
    add constraint SAMPLE_CONS3_CHECK_pk primary key (NAME)
    ALTER TABLE SAMPLE_CONS3_CHECK ADD
    CONSTRAINT SAMPLE_CONS3_CHECK_FK1 FOREIGN KEY
         NAME
    ) REFERENCES SAMPLE_CONS_CHECK
        NAME
    ) ON DELETE CASCADE;
    ALTER TABLE SAMPLE_CONS3_CHECK ADD
    CONSTRAINT SAMPLE_CONS3_CHECK_FK2 FOREIGN KEY
         NAME
    ) REFERENCES SAMPLE_CONS2_CHECK
        NAME
    ) ON DELETE CASCADE;From the above schenario i am able to insert the data to SAMPLE_CONS3_CHECK table. But the parent data is already available in the parent table. The problem is here two different constarints from two different tables. While inserting, it is checking from both the tables whether the parent is exist or not.
    How can i solve this problem? Can anyone halp me about this?
    Thanks
    Edited by: orasuriya on Aug 8, 2009 2:02 AM

    Actually the design is completely incorrect.
    What you say is
    I have
    'foo', 'foo series'
    'foo','foo model'
    'foo',666
    By virtue of table3 referring to both table1 and table2.
    This means you actually need to have 1 (one) table:
    'foo','foo series','foo model', 666
    And the 'problem' disappears.
    Sybrand Bakker
    Senior Oracle DBA

  • OBIEE 11g - Combine data from two Oracle tables

    Good day!
    I tried to combine data from two Oracle tables as fact data, but it doesn't work.
    My steps: I created SCOTT.EMP2 table from SCOTT.EMP table, update EMPNO and ENAME values of EMP2 table to distinguish data of my tables. Then I imported physical tables DEPT, EMP and EMP2 to BIEE 11g, created joins DEPT-EMP and DEPT-EMP2 in physical diagram. Then I dragged DEPT and EMP tables to BMM, and EMP2 table to EMP as second LTS. In Content tab for EMP and EMP2 I checked "This source should be combined with other sources at this level" checkboxes. Then I renamed logical tables EMP and DEPT to Employees and Departments and dragged them to Presentation area. In Answers I created Analysis with columns DNAME and ENAME.
    The problem is that data on results tab is only from one physical table EMP or EMP2 (depending on the order of sources EMP and EMP2 of LT Employees) and not from both.
    Can anybody help? Am I missed something?
    Al.

    Hi Al,
    I think you have to define the content of the LTS.
    http://download.oracle.com/docs/cd/E12096_01/books/admintool/admintool_BusModSetup16.html
    You have to specify the content of the different fragments.
    http://download.oracle.com/docs/cd/E12096_01/books/admintool/admintool_SetUpAggNav3.html#wp1005333
    Maybe you have to add an additional column 'Source' ('EMP1', 'EMP2')
    Good Luck,
    Daan Bakboord
    http://obibb.wordpress.com

  • Selecting data from two different tables.

    Do we need to use join two tables with primary/foreign key while trying to use select statement for getting data from those to table.? If no who can i go about do it.

    872959 wrote:
    If i am using From clause to get data from two different tables, is it necessary that both tables have column of identical data in them.In general, they ought to (or you need to join in a third table that tells you how to map rows from one table to rows of the other table).
    It is not strictly necessary that there be any join condition between tables. If you don't provide a join condition, Oracle has to do a Cartesian product. That means that if there are n rows in one table and m rows in the other, the result set will have n * m rows. It is very rarely a good idea to write queries that do Cartesian products but it does occasionally happen.
    Justin

  • Lgical table from two physical table

    Hi,
    I am trying to design a logical fact table from two physical table. One table has transaction data and another has accounting data. The requirement is, I need to merge the rows between these two tables, where were it matches. If the keys are not matching between these two table then also I need to bring those rows from both tables as separate rows. How can i do this? Also can i have a logical table as source for my fact table.

    You'll need outer joins in your physical layer and you can drag the columns from both physical tables to a single logical table and you will see in the BMM layer it will create the two logical table sources.

  • Can i access my data on time capsule from some other network

    can i access my data on time capsule from some other network that is my data at home from office over internet

    There is plenty of info out there if you google..
    Here is a summary I just put into another thread.
    Remote access has been added back into iCloud that was in MobileMe..
    Read the info on setting it up from cloud service.. BTMM.
    http://www.apple.com/support/icloud/back-to-my-mac/
    If you want to do it without the cloud service, you have one major issue.. the public IP for WAN..
    The internal IP of the TC.. which will default to 10.0.1.1 btw.. is irrelevant. It is the IP of the WAN which you use to access the TC over the internet. And here you have a problem.. the TC does not include dyndns service. So unless you have a static IP address from your ISP, this will cause you grief.
    (If it is offered by your ISP.. get a static IP.. that eliminates all the issues.. and is far superior. Even dyndns service has issues if your public IP rotates too often. It is generally an extra cost item and requires a business account but some ISP offer it cheap or even free.. I joined an ISP that offered static ip for free because it gives me the ability to remote access my network without all the hassles you will see below.)
    There are ways around it.. setting up your own domain for instance.
    http://dyn.com/support/airport-time-capsule-with-dynamic-dns/
    But it is easier to simply use a different router.. almost all of them have dyndns service available.. place the TC behind the router in bridge and forward port 548 TCP to it.
    This is a bit old but still relevant.
    http://gigaom.com/apple/access-your-time-capsule-over-the-internet/
    Note .. there is no ftp, http, ssh (there is actually but it isn't accessible), or any other service to allow connection other than AFP.. so you must use a Mac in remote location to access the TC.
    The setup for the two methods is slightly different in the TC.. in the first instance, you need to turn on WAN access via disk sharing page in the manual setup.
    In the second case you do not need this.
    Remember security and put strong passwords on the disk. There are still security questions about this.
    If security is important.. there is a third and better (IMO) method and that is vpn.. you will need to buy a vpn router as TC also missed out on that.. establish a vpn with the main router and that will allow you access to your network.. you will also then be able to use SMB remotely not just AFP.
    Also if this office is a large company they should be running a firewall, which would block your access to home. You should check your IT admin people for what is allowed.. generally the only acceptable method is vpn otherwise you can drag viruses and trojans right into the network without the firewall catching them.

  • From two given tables, how do you fetch the values from two columns using values from one column(get values from col.A if col.A is not null and get values from col.B if col.A is null)?

    From two given tables, how do you fetch the values from two columns using values from one column(get values from col.A if col.A is not null and get values from col.B if col.A is null)?

    Hi,
    Use NVL or COALESCE:
    NVL (col_a, col_b)
    Returns col_a if col_a is not NULL; otherwise, it returns col_b.
    Col_a and col_b must have similar (if not identical) datatypes; for example, if col_a is a DATE, then col_b can be another DATE or it can be a TIMESTAMP, but it can't be a VARCHAR2.
    For more about NVL and COALESCE, see the SQL Language manual: http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions119.htm#sthref1310
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, and also post the results you want from that data.
    Explain, using specific examples, how you get those results from that data.
    Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
    See the forum FAQ: https://forums.oracle.com/message/9362002

  • Adding count from two select statements

    Hi,
    How to add counts from two select statements in a single SQL statement.
    For ex: I have
    SELECT COUNT(DISTINCT COL1) FROM table1
    and
    SELECT COUNT(DISTINCT COL2) FROM table2.
    I want to add the counts from these two sqls in a single select query. How to do this.
    Thanks & Regards,
    Sunil.

    select ((SELECT COUNT(DISTINCT COL1) FROM table1) + (SELECT COUNT(DISTINCT COL2) FROM table2)) as "total" from dual;
    regards,

  • Populate ADF Rich Table taking data from two tables of database

    Hi,
    Can anyone please guide me as to how I can populate ADF Rich Table taking data from two tables A and B of a database.
    The condition is
    I want to fetch row 1 from table A and populate into ADF Rich Table at row 1
    then
    I want to fetch row 1 from table B and populate into ADF Rich Table at row 2
    and so on....
    Many thanks for your help..
    Regards,
    Rohit

    The better place where you will learn:
    http://download.oracle.com/docs/cd/E12839_01/web.1111/b31974/bcquerying.htm

  • HT1911 If I make a new iTunes account with the same credit card number can I still have the same thing I bought from my other account?

    If I make a new iTunes account with the same credit card number can I still have the same thing I bought from my other account?

    Not without buying them from the new iTunes Store account.
    (84283)

Maybe you are looking for