Help in joining results

hi experts,
i am newbie, please help me with my sql query
table1
id X
1 1
2 1
3 1
1 1
3 1
table2
id Y
1 1
2 1
4 1
5 1
2 1
required output
id X Y
1 2 1
2 1 2
3 2 0
4 0 1
5 0 1
my following query produces wrong output, please help me to correct/rewrite it
select id, count(X) from table1 group by id, X
union
select id, count(Y) from table1 group by id, X
many thanks
Raj

One possible way:
SQL> with table1 as (
  2     select 1 id, 1 X from dual union all
  3     select 2, 1 from dual union all
  4     select 3, 1 from dual union all
  5     select 1, 1 from dual union all
  6     select 3, 1 from dual
  7  ), table2 as (
  8     select 1 id, 1 Y from dual union all
  9     select 2, 1 from dual union all
10     select 4, 1 from dual union all
11     select 5, 1 from dual union all
12     select 2, 1 from dual
13  )
14  --
15  -- end of test data
16  --
17  select
18  nvl(tx.id,ty.id) id,
19  nvl(tx.x,0) x,
20  nvl(ty.y,0) y
21  from (
22     select id, sum(X) X from table1 group by id
23  ) tx
24  full outer join
25  (
26     select id, sum(Y) Y from table2 group by id
27  ) ty
28  on (
29     ty.id = tx.id
30  )
31  order by
32  nvl(tx.id,ty.id);
        ID          X          Y
         1          2          1
         2          1          2
         3          2          0
         4          0          1
         5          0          1

Similar Messages

  • Help with Joining a few tables

    I need a help using JOINS. I plan to create ONE VIEW by bringing in all fields from First and Second table and a few chosen columns from Third, Fourth and Fifth tables. I have put to together below select statement which appears to be working syntax-wise but not efficient and may have dupes.
    Table1 - RPT_APRL_PRODUCT with key field KEY_MATERIAL (KEY_MATERIAL = DIVISION||PLAN_CTRY||MKT_TYP_ID||MATERIAL)
    Table 2 - RPT_FWEQ_PRODUCT with key field KEY_MATERIAL (KEY_MATERIAL = DIVISION||PLAN_CTRY||MATERIAL)
    Table 3 - NSC_PROD_CIMG has a Key Field = MATERIAL_NBR
    Table 4- STAGE#EMEA_NSAP.NSC_PROD_REG_CIMG has the Key field MATERIAL_NBR, REG_ID
    Table 5 - STAGE#EMEA_NSAP.NSC_PROD_REG_CYC_CIMG has Key Fields MATERIAL_NBR, REG_ID, CYC_ID and ORGVERSIONID
    Columns needed from Table 3 -- B.DIVISION, B.DIVISIONNAME, B.SUBLABEL, B.SUBLABELNAME and B.DEVELOPMENTREGION.
    Columns needed from Table 4 --- C.GLOBALSOURCEINDICATOR
    Columns needed from Table 5--- D.CARRYOVERFLAG
    SELECT statement:
    SELECT /*+ parallel (a,5) parallel (NET,5) */
    a.key_material,
    a.mkt_typ_id,
    a.region_id,
    CASE
    WHEN a.region_id = '3' THEN 'USA'
    WHEN a.region_id = '4' THEN 'EMEA'
    WHEN a.region_id = '7' THEN 'CANADA'
    END AS region_desc,
    a.mkt_reg_cd,
    CASE
    WHEN a.mkt_reg_cd = '01' THEN 'USA'
    WHEN a.mkt_reg_cd = '02' THEN 'EMEA'
    WHEN a.mkt_reg_cd = '05' THEN 'AMER'
    END AS mkt_reg_desc,
    a.cat_bus_cd1,
    a.cat_bus_desc1,
    a.cat_bus_cd2,
    a.cat_bus_desc2,
    a.cat_bus_cd3,
    a.cat_bus_desc3,
    a.cat_bus_cd4,
    a.cat_bus_desc4,
    a.mkstr_cd,
    a.mkt_clsfn_desc,
    a.mkt_clsfn_cd1,
    a.mkt_clsfn1_desc,
    a.mkt_clsfn_cd2,
    a.mkt_clsfn2_desc,
    a.mkt_clsfn_cd3,
    a.mkt_clsfn3_desc,
    a.exp_sty_ind,
    a.silh_cd,
    a.silh_desc,
    a.whlsl_prc,
    0,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    a.gender_age_class_id,
    a.gender_age_desc,
    a.sports_activity_class_id,
    a.sports_act_cls_desc,
    a.gblcatsummcode,
    a.gblcatsummdesc,
    a.gblcatcorefocuscode,
    a.gblcatcorefocusdesc,
    a.segment,
    a.segmentname,
    a.l4l_fl,
    NET.DIVISION,
    NET.DIVISIONNAME,
    NET.SUBLABEL,
    NET.SUBLABELNAME,
    NET.DEVELOPMENTREGION,
    NULL,
    NULL,
    NULL,
    NET.globalsourceindicator,
    NET.CARRYOVERFLAG,
    a.zz_chng_tmst,
    a.zz_update_tmst,
    a.zz_insert_tmst
    FROM RPT_APRL_PRODUCT A,
    (SELECT
    APRL.DIVISION||APRL.PLAN_CTRY||APRL.MKT_TYP_ID||APRL.MATERIAL ; AS KEY_MATERIAL,
    B.DIVISION,
    B.DIVISIONNAME,
    B.SUBLABEL,
    B.SUBLABELNAME,
    B.DEVELOPMENTREGION,
    C.GLOBALSOURCEINDICATOR,
    D.CARRYOVERFLAG
    from RPT_APRL_PRODUCTAPRL,
    NSC_PROD_CIMG B,
    NSC_PROD_REG_CIMG C,
    NSC_PROD_REG_CYC_CIMG D
    where APRL.MATERIAL = B.MATERIAL_NBR AND
    APRL.MATERIAL = C.MATERIAL_NBR AND
    APRL.MATERIAL = D.MATERIAL_NBR AND
    C.REG_ID = D.REG_ID) NET
    WHERE A.KEY_MATERIAL = NET.KEY_MATERIAL(+)
    Thanks for help in advance.

    I have 4 tables and these are some sample data for
    RPT_APRL_PRODUCT - Key Field = KEY_MATERIAL (this is a combination of plan_ctry,division,mkt_typ_id and material)
    Sample data
    KEY_MATERIAL          PLAN_CTRY   DIVISION  MKT_TYP_ID              MATERIAL
    10PART1136353-010      PART          10              1                      136353-010
    10AMER1136353-010      AMER          10              1                      136353-010
    10USA1136353-010       USA           10              1                      136353-010
    10CANA1136353-010      CANA          10              1                      136353-010
    10PART1137508-050      PART          10              1                      137508-050
    10AMER1137508-050      AMER          10              1                      137508-050
    10CANA1137508-050      CANA          10              1                      137508-050
    10USA1137508-050       USA           10              1                      137508-050
    10PART1137617-050      PART          10              1                      137617-050
    10AMER1137617-050      AMER          10              1                       137617-050nsc_prod_reg_cimg - keys (material_nbr and reg_id)
    MATERIAL                REG_ID          GLOBALSOURCEINDICATOR
    136353-010      3                                     G
    136353-010      6                                     G
    136353-010      7                                    
    137508-050      3                                    
    137508-050      6                                     G
    137508-050      7                                    
    137508-050      46                                    G
    137617-050      3                                    
    137617-050      6                                    
    137617-050      46                                    nsc_prod_reg_cyc_cimg - key is material_nbr, cyc_id, reg_id and orgversion_id
    MATERIAL_NBR       CYC_ID                    orgversion_id                                reg_ID                CARRYOVERFLAG
    136353-010      101                             1                                          3                             Y       
    136353-010      101                              1                                          6                             Y      
    136353-010      101                               1                                          7                             N      
    137508-050      202                               1                                          3                             Y     
    137508-050      202                               1                                          6                             N       
    137508-050      202                               1                                          7                                    
    137617-050      205                               1                                          3                                    
    137617-050      205                               1                                          6                                    
    185204-402      181                              1                                          8                                    
    185204-402      182                               1                                          8                                     nsc_prod_cimg - key is material_nbr
    MATERIAL_NBR     SUBLABEL     SUBLABELNAME
    136353-010           
    137508-050                GD           Good
    137617-050
    185204-402
    185204-402
    185204-402                BE            Better
    185204-402
    185204-402
    185204-402               CO            Core
    185204-402               BS             BestWhat I intend to do, is to create one view by joining these four tables. The columns key_material, plan_ctry, division and MKT_TYP_ID come from RPT_APRL_PRODUCT. I need to join these tables in such a way that I bring in the other 1 or 2 columns each from the 3 tables as described above. The result should have a unique key_material and have the other column data in the view as well.
    Result should be all the columns described above, something like this below...
    KEY_MATERIAL          PLAN_CTRY   DIVISION  MKT_TYP_ID              MATERIAL      SUBLABELNAME  CARRYover_FL
    10PART1136353-010      PART          10              1                      136353-010
    10AMER1136353-010      AMER          10              1                      136353-010

  • HELP - Query Join Problem

    I am trying to write a query to return data from 4 different tables and it is doubling my summed values. I can get the separate queries to work, but not combined and I need them combined so that I can get a balance due and limit the records to only those that had a total billed (fees) less than $200.
    Query #1 Gets the total of the fees due for each appeal type and invoice:
    Note: There is always at least one fee attached to an invoice.
    SELECT APT.APTY_DESCR "APPEAL TYPE",
    INV.INVC_ID_SEQ INVOICE,
    SUM( ALL FEE.AMT_DUE) "TOTAL BILLED AMOUNT"
    FROM WRD_APPEALS AP,
    WRD_INVOICES INV,
    WRD_FEES_DUE FEE,
    WRD_APPEAL_TYPES APT
    WHERE AP.APST_CD = 'PEND'
    AND AP.INVC_ID_SEQ = INV.INVC_ID_SEQ
    AND AP.INVC_ID_SEQ = FEE.INVC_ID_SEQ
    AND AP.APTY_CD = APT.APTY_CD
    GROUP BY APT.APTY_DESCR, INV.INVC_ID_SEQ
    ORDER BY APT.APTY_DESCR, INV.INVC_ID_SEQ
    4     BILLING CATEGORY INCORRECT     4147     1200
    5     BILLING CATEGORY INCORRECT     4203     1100
    6     BILLING CATEGORY INCORRECT     4216     72600
    7     BILLING CATEGORY INCORRECT     4826     1000
    8     BILLING CATEGORY INCORRECT     4951     2060
    Query #2 Gets the total amount paid for each appeal type and invoice:
    Note: An invoice may or may not have a payment, thus the outer join.
    SELECT APT.APTY_DESCR "APPEAL TYPE",
    INV.INVC_ID_SEQ INVOICE,
    SUM(ALL PMT.PAID_AMT) "AMOUNT PAID"
    FROM WRD_APPEALS AP,
    WRD_INVOICES INV,
    WRD_APPEAL_TYPES APT,
    WRD_PAYMENTS PMT
    WHERE AP.APST_CD = 'PEND'
    AND AP.INVC_ID_SEQ = INV.INVC_ID_SEQ
    AND AP.APTY_CD = APT.APTY_CD
    AND INV.INVC_ID_SEQ = PMT.INVC_ID_SEQ(+)
    GROUP BY APT.APTY_DESCR, INV.INVC_ID_SEQ
    ORDER BY APT.APTY_DESCR, INV.INVC_ID_SEQ
    4     BILLING CATEGORY INCORRECT     4147     200
    5     BILLING CATEGORY INCORRECT     4203     0
    6     BILLING CATEGORY INCORRECT     4216     72600
    7     BILLING CATEGORY INCORRECT     4826     
    8     BILLING CATEGORY INCORRECT     4951     
    Combined Query - Gets all of the above as well as the balance due. Note the doubled values for some records.
    SELECT APT.APTY_DESCR "APPEAL TYPE",
    INV.INVC_ID_SEQ INVOICE,
    SUM( ALL FEE.AMT_DUE) "TOTAL BILLED AMOUNT",
         SUM(ALL PMT.PAID_AMT) "AMOUNT PAID",
         (SUM(ALL FEE.AMT_DUE) -
         NVL2(SUM(ALL PMT.PAID_AMT), SUM(ALL PMT.PAID_AMT), 0)) "BALANCE DUE"
    FROM WRD_APPEALS AP,
    WRD_INVOICES INV,
    WRD_FEES_DUE FEE,
    WRD_APPEAL_TYPES APT,
         WRD_PAYMENTS PMT
    WHERE AP.APST_CD = 'PEND'
    AND AP.INVC_ID_SEQ = INV.INVC_ID_SEQ
         AND INV.INVC_ID_SEQ = PMT.INVC_ID_SEQ(+)
         AND INV.INVC_ID_SEQ = FEE.INVC_ID_SEQ
         AND AP.APTY_CD = APT.APTY_CD
    GROUP BY APT.APTY_DESCR, INV.INVC_ID_SEQ
    ORDER BY APT.APTY_DESCR, INV.INVC_ID_SEQ,
    4     BILLING CATEGORY INCORRECT     4147     1200     400     800
    5     BILLING CATEGORY INCORRECT     4203     2200     0     2200
    6     BILLING CATEGORY INCORRECT     4216     72600     435600     -363000
    7     BILLING CATEGORY INCORRECT     4826     1000          1000
    8     BILLING CATEGORY INCORRECT     4951     2060          2060
    HELP PLEASE!
    Thank you.

    When you have multiple child rows, the parent row gets returned once for each child row found. Therefore, if you have summed the invoice, it gets summed again for each payment. Perhaps this little example will help you understand the problem.
    Note that I used a sub query here to obtain the desired results. Analytic functions can do the same I believe, but I am still learning them :-)
      D> DROP TABLE DMILL.invoice;
    Table dropped.
      D>
      D> DROP TABLE DMILL.payments;
    Table dropped.
      D>
      D> CREATE TABLE invoice AS
         SELECT 1 id, 10 amount FROM DUAL UNION ALL
         SELECT 2 id, 10  FROM DUAL UNION ALL
         SELECT 2 id, 10  FROM DUAL UNION ALL
         SELECT 3 id, 10  FROM DUAL;
    Table created.
      D>
      D> CREATE TABLE payments AS
         SELECT 1 inv_id, 5 amount FROM DUAL UNION ALL
         SELECT 1 inv_id, 5 amount FROM DUAL UNION ALL
         SELECT 2 inv_id, 5 amount FROM DUAL UNION ALL
         SELECT 2 inv_id, 5 amount FROM DUAL UNION ALL
         SELECT 2 inv_id, 5 amount FROM DUAL;
    Table created.
      D>
      D> select * from invoice;
            ID     AMOUNT
             1         10
             2         10
             2         10
             3         10
      D>
      D> select * from payments;
        INV_ID     AMOUNT
             1          5
             1          5
             2          5
             2          5
             2          5
      D>
      D> select id
                  ,sum (amount)
          from  invoice
         group by id;
            ID SUM(AMOUNT)
             1          10
             2          20
             3          10
      D>
      D> select inv_id
                  ,sum(amount)
          from  payments
         group by inv_id;
        INV_ID SUM(AMOUNT)
             1          10
             2          15
      D>
      D> select inv.id
                  ,inv.amount
                  ,pay.amount
          from invoice  inv
                 ,payments pay
         where pay.inv_id = inv.id;
            ID     AMOUNT     AMOUNT
             1         10          5
             1         10          5
             2         10          5
             2         10          5
             2         10          5
             2         10          5
             2         10          5
             2         10          5
    8 rows selected.
      D>
      D> select inv.id
                  ,sum(inv.amount)
                  ,sum(pay.amount)
          from invoice  inv
                 ,payments pay
         where pay.inv_id = inv.id
         group by inv.id;
            ID SUM(INV.AMOUNT) SUM(PAY.AMOUNT)
             1              20              10
             2              60              30
      D>
      D> select inv.id
                  ,sum(inv.amount)
                  ,(SELECT sum(pay.amount)
                    FROM   payments pay
                    WHERE  pay.inv_id = inv.id)
          from invoice  inv
         group by inv.id;
            ID SUM(INV.AMOUNT) (SELECTSUM(PAY.AMOUNT)FROMPAYMENTSPAYWHEREPAY.INV_ID=INV.ID)
             1              10                                                           10
             2              20                                                           15
             3              10Let me know if you need further explanation.

  • Need help in joins in OBIEE 10G

    Hi All,
    I have 2 tables like following.
    Table 1: Team
    Id| Team Name| Resource id
    1 | xxx | 1
    2 | yyy | 1
    3 | zzz | 1
    4 | xxx | 2
    Table 2: Resource Rate
    RSRC ID| Resource Name| Rate | Month | year
    1 | John | 10 | Jan | 2012
    2 | Max | 5 | Jan | 2012
    I have joined these 2 tables with Resource ID. I have a prompt with Team Name and Resource Name and I have a OBIEE chart report (Month,Year Vs Rate), in which if do not select team name in prompt or select only one team name then the results are fine but when i select 2 team names in the prompt for example 'xxx','yyy' the results gets doubled. If I select 3 team names, the result will be rate*3. But I want the result to be same value even after I select more than one team name.
    How to archive this??? Kindly help
    Edited by: GJ on Sep 10, 2012 10:39 PM
    Edited by: GJ on Sep 10, 2012 11:53 PM

    Hi Veeravalli,
    No I cannot have team name after resource name, because the purpose is to see based on team and then on resource. Moreover their is nothing wrong with queries generated, it is working as it is expected, Since the resource is mapped to 2 teams, I am getting duplicate values.
    I am just trying to find if there is a way to return always unique values.

  • Help in Joining query

    Hi, How I can get desired result. I am joining two tables but if date timeline does't exist in #two table then should show hyphen (-). Please help on this query. Thanks.
    create table #one (code_p char(4), code_h char(2), code_date datetime)
    insert into #one values ('DEHG','2','2010-01-01')
    insert into #one values ('DEHG','2','2011-01-01')
    insert into #one values ('DEHC','2','2009-01-01')
    insert into #one values ('DEHG','2','2012-01-01')
    create table #two (code_p char(4), code_h char(2), code_date datetime)
    insert into #two values ('DEHG','2','2010-01-01')
    insert into #two values ('DEHC','2','2009-01-01')
    select p.code_p code_p_one, p.code_h code_h_one, p.code_date code_date_one,
    p.code_p code_p_two, p.code_h code_h_two, p.code_date code_date_two from #one p join #two a on p.code_p = a.code_p
    --Result from the above query
    code_p_one code_h_one code_date_one code_p_two code_h_two code_date_two
    DEHG     2    2010-01-01     DEHG     2     2010-01-01
    DEHG     2    2011-01-01     DEHG     2     2010-01-01
    DEHC     2    2009-01-01     DEHG     2     2009-01-01
    DEHC     2    2012-01-01     DEHG     2     2009-01-01
    --Desired result
    code_p_one code_h_one code_date_one code_p_two code_h_two code_date_two
    DEHG     2    2010-01-01     DEHG     2     2010-01-01
    DEHG     2    2011-01-01     DEHG     2     -
    DEHC     2    2009-01-01     DEHG     2     2009-01-01
    DEHC     2    2012-01-01     DEHG     2     -

    Try this:
    select p.code_p code_p_one, p.code_h code_h_one, p.code_date code_date_one,
    p.code_p code_p_two, p.code_h code_h_two, ISNULL(CONVERT(varchar(50),a.code_date,121),'-') code_date_two
    from #one p
    left join #two a on p.code_p = a.code_p and p.code_date=a.code_date
    If this post answers your query, please click "Mark As Answer" or "Vote as Helpful".

  • I need a help on Join please or anybody help to rewrite the query

    select
    x.QUEST_DESC,y.QUES_RESPONSE, y.user_id from
    (select c.QUES_CODE, c.QUEST_DESC, null user_id from CLINICAL_HISTORY_QUESTIONS c where c.CLINICAL_TYPE_CODE=2) x,
    (select a.QUEST_CODE, a.QUEST_RESPONSE, a.user_id from PATIENT_CLINICAL_HISTORIES a where a.CLINICAL_TYPE_CODE=2 and a.user_ID=88) y
    where x.QUEST_CODE =y.QUEST_CODE(+)
    Is there any way I can display same user_ID 88 on the null USER_ID (Joined one)
    my result is
    QUEST_DESC     QUEST_RESPONSE     USER_ID
    Fibrostenotic               U     88
    Inflammatory               U     88
    Int Penetrating/Perforating          U     88
    Perianal Perforating Disease          U     88
    Uc Like                    U     88
    Iv Therapy          
    Fistula          
    Bleeding          
    Osteopenia          
    Sibo          
    Urgency          
    Extraintestinal Sx          
    Steroid Dependent          
    Immunosuppressive Tx          
    Fever/Chills          
    Obstructive Sx          
    Stool Consistency          
    Adb Pain          
    Other          
    Growth          
    Osteoporosis          
    Stool Frequency          
    Flare Of Disease
    Edited by: Paul Vellackel on Jul 2, 2010 3:20 PM
    Edited by: Paul Vellackel on Jul 2, 2010 3:55 PM

    sigh
    What we were asking you is to post data we can work with rightaway, so CREATE TABLE statement, and INSERT INTO statement. So: not output, but statements...
    Since I'm in a good mood (we're in the semi finals ;) ), here's an example of how you should post your data:
    create table a1 as
    select 1 quest_code, 'Fibrostenotic' quest_desc from dual union
    select 2, 'Inflammatory' from dual union
    select 3, 'Int Penetrating/Perforating' from dual union
    select 4, 'Perianal Perforating Disease' from dual union
    select 5, 'Uc Like' from dual union
    select 6, 'Flare Of Disease' from dual union
    select 7, 'Immunosuppressive Tx' from dual union
    select 8, 'Iv Therapy' from dual union
    select 9, 'Stool Consistency' from dual union
    select 10, 'Urgency' from dual union
    select 11, 'Stool Frequency' from dual union
    select 12, 'Bleeding' from dual union
    select 13, 'Adb Pain' from dual union
    select 14, 'Fever/Chills' from dual union
    select 15, 'Fistula' from dual union
    select 16, 'Obstructive Sx' from dual union
    select 17, 'Extraintestinal Sx' from dual union
    select 18, 'Steroid Dependent' from dual union
    select 19, 'Sibo' from dual union
    select 20, 'Osteoporosis' from dual union
    select 21, 'Osteopenia' from dual union
    select 22, 'Growth' from dual union
    select 23,  'Other' from dual;
    create table a2 as
    select 1 quest_code, 'U' quest_response, 88 user_id from dual union
    select 2, 'U', 88 from dual union
    select 3, 'U', 88 from dual union
    select 4, 'U', 88 from dual union
    select 5, 'U', 88 from dual;
    create table a3 as
    select 'testuserb' user_name, 88 user_id from dual;Posted like that, we can copy+paste and try to help you rightaway instead of waisting time formatting, putting quotes right etc. etc.
    Also use the {noformat}{noformat} tag when you post an example.
    That way it will stay formatted and indented.
    So, when you type: {noformat}select *
    from dual;{noformat}
    it will appear as: select *
    from dual;when you post it.
    Finally, perhaps you could try something like this:SQL> select a1.quest_desc
    2 , a2.quest_response
    3 , case
    4 when (select a3.user_id
    5 from a3
    6 where a3.user_id = a2.user_id) is not null
    7 then (select a3.user_id
    8 from a3
    9 where a3.user_id = a2.user_id)
    10 else (select a3.user_id
    11 from a3
    12 where a3.user_name = 'testuserb')
    13 end user_id
    14 from a1
    15 , a2
    16 where a1.quest_code = a2.quest_code(+);
    QUEST_DESC Q USER_ID
    Fibrostenotic U 88
    Inflammatory U 88
    Int Penetrating/Perforating U 88
    Perianal Perforating Disease U 88
    Uc Like U 88
    Iv Therapy 88
    Fistula 88
    Bleeding 88
    Osteopenia 88
    Sibo 88
    Urgency 88
    Extraintestinal Sx 88
    Steroid Dependent 88
    Immunosuppressive Tx 88
    Fever/Chills 88
    Obstructive Sx 88
    Stool Consistency 88
    Adb Pain 88
    Other 88
    Growth 88
    Osteoporosis 88
    Stool Frequency 88
    Flare Of Disease 88
    23 rows selected.

  • View with outer join results wrong number of rows

    Hi,
    When i run a query on a view it returns 2 rows(2 distinct rows), when i run the same query with the select statement which the view is created , it returns only 1 row. According to data the 1 row result is correct, how come twi results. A coding sample as follows. Any help is most appreciated.
    I have a view created based on a outer join of two views in the format;
    create or replace view view1 as
    select ord.order_no order_no,
    ord.del_type del_type,
    det.qty qty
    from detail_view det, order_view ord
    where det.site(+) = ord.site
    and det.part(+) = ord.part
    and nvl(ord.del_type,'_NULL_') <> 'F'
    with read only;
    detail_view & order_view themselves have several group by/sum and union Alls.
    When i run the query on this view
    [Select * from View1 where order_no = 'A30' And del_type = 'B']
    it returns 2 distinct rows. But when i run the select statement which created the View1 with the query it returns only one row!!
    What did i do wrong?
    Thanks
    Sanjeewa

    I cannot reproduce this :
    SCOTT@LSC01> create table detail_view(qty number,site number,part number);
    Table created.
    SCOTT@LSC01> create table order_view(order_no varchar2(10), del_type varchar2(1), site number,part number);
    Table created.
    SCOTT@LSC01>
    SCOTT@LSC01> create or replace view view1 as
      2  select ord.order_no order_no,
      3  ord.del_type del_type,
      4  det.qty qty
      5  from detail_view det, order_view ord
      6  where det.site(+) = ord.site
      7  and det.part(+) = ord.part
      8  and nvl(ord.del_type,'_NULL_') <> 'F'
      9  with read only;
    View created.
    SCOTT@LSC01>
    SCOTT@LSC01> insert into order_view values ('A30','B',1,2);
    1 row created.
    SCOTT@LSC01> insert into order_view values ('A30','B',1,2);
    1 row created.
    SCOTT@LSC01>
    SCOTT@LSC01> Select * from View1 where order_no = 'A30' And del_type = 'B';
    ORDER_NO   D        QTY
    A30        B
    A30        B
    SCOTT@LSC01>
    SCOTT@LSC01> select ord.order_no order_no,
      2  ord.del_type del_type,
      3  det.qty qty
      4  from detail_view det, order_view ord
      5  where det.site(+) = ord.site
      6  and det.part(+) = ord.part
      7  and nvl(ord.del_type,'_NULL_') <> 'F' ;
    ORDER_NO   D        QTY
    A30        B
    A30        Bwhat is your version?

  • Help with joins

    Hi,
    I am not sure if I am doing something wrong here, but would appreciate if someone point out my mistake.
    I have two table item and item_status
    item_status do not contain all the items but only the ones which have specific status
    Question(1):
    select count(*) from item
    and
    select count(*) from item left join item_status on item.itemid = item_status.item_id
    Result of these two queries dont match. Can you'll plz help me understand it.
    Question(2):
    I want count of items from table item by location (location is another field in table item) but I want to exclude items which have status lost in the item_status table.
    This is the query I used:
    select location, count(*) from item left join item_status on item.itemid = item_status.item_id where item_status.status = 'lost'
    is this the correct way, coz when I tried the figures where way to low,
    Thanks,
    Raja

    Hi, Raja,
    Raja Gopalan wrote:
    Hi,
    I am not sure if I am doing something wrong here, but would appreciate if someone point out my mistake.
    I have two table item and item_status
    item_status do not contain all the items but only the ones which have specific status
    Question(1):
    select count(*) from item
    and
    select count(*) from item left join item_status on item.itemid = item_status.item_id
    Result of these two queries dont match. Can you'll plz help me understand it.If there can be many rows in item_status that all match the same row in item, then the 2nd query will have a higher COUNT than the first.
    If you'd post your tables, I could show you in detail.
    Since you didn't I'll use tables from the scott schema.
    SELECT  d.deptno
    FROM     scott.dept     d;produces 4 rows:
    .   DEPTNO
            10
            20
            30
            40Only 3 of these rows have a match in the mep table, but the ones that match have many matches.
    SELECT     d.deptno
    ,     e.ename
    FROM          scott.dept     d
    LEFT OUTER JOIN     scott.emp     e     ON     d.deptno     = e.deptno;produces 15 rows
    .   DEPTNO ENAME
            20 SMITH
            30 ALLEN
            30 WARD
            20 JONES
            30 MARTIN
            30 BLAKE
            10 CLARK
            20 SCOTT
            10 KING
            30 TURNER
            20 ADAMS
            30 JAMES
            20 FORD
            10 MILLER
            401 row for each row in emp that has a match in dept (that is all 14 rows in emp) plus 1 row for every row in dept that does not have a match in emp (1 row).
    Question(2):
    I want count of items from table item by location (location is another field in table item) but I want to exclude items which have status lost in the item_status table.
    This is the query I used:
    select location, count(*) from item left join item_status on item.itemid = item_status.item_id where item_status.status = 'lost'
    is this the correct way, coz when I tried the figures where way to low,If you want a count by location, then you should say "GROUP BY location".
    You probably need a sub-query to check for 'lost'. Without seeing your tables and data, I can't be sure.
    Maybe something like
    SELECT  location
    ,     COUNT (*)
    FROM     item
    WHERE     itemid     NOT IN     (     -- Begin subquery to find bad item_ids
                       SELECT  item_id
                   FROM     item_status
                   WHERE     status     = 'lost'
                       )     -- End subquery to find bad item_ids
    GROUP BY  location
    ;

  • Help with joining one table to several

    I have the following table
    MSELECT
    Res_ID
    Res_type
    34
    501
    56
    501
    72
    501
    81
    502
    90
    502
    100
    502
    47
    503
    48
    503
    The RES_ID will link to different tables such as tablea, tableb or tablec based on the RES_Type value .g. RES_Type ID 501 will link to tableA and 502 will link to TableB and 503 will link to TableC.
    I have created the following query:
    Select * from MSSELECT MSEL
    Inner join tablea  ta on
    Ta.id = MSEL.ID and
    Res_type = 501
    Inner join tableb tb on
    Tb.id = MSEL.ID and
    Res_type = 501
    If I run the following query then results are returned.
     Select * from MSSELECT MSEL
    Inner join tablea  ta on
    Ta.id = MSEL.ID and
    Res_type = 501
    However if I run the following query it is returning no results:
    Select * from MSSELECT MSEL
    Inner join tablea  ta on
    Ta.id = MSEL.ID and
    Res_type = 501
    Inner join tableb tb on
    Tb.id = MSEL.ID and
    Res_type = 501

    Try:
    Select * from MSSELECT MSEL
    LEFT OUTER join tablea  ta on
    Ta.id = MSEL.ID and
    Res_type = 501
    LEFT OUTER  join tableb tb on
    Tb.id = MSEL.ID and
    Res_type = 501
    Best Wishes, Arbi; Please vote if you find this posting was helpful or Mark it as answered.

  • Help in joining two tables

    Hi ,
    I need your help in the below scenario:
    I have two tables.
    One of my table 'table1' contains the below data:
    Code:
    Name,Value
    12A,1
    12B,1
    12C,1
    Table2 contains the below data:
    Code:
    value,result
    1,12
    1,24
    1,56
    1,423
    1,32
    1,3
    I need to join based on value field.
    My expected result is:
    Code:
    NAME,VALUE,RESULT
    12A,1,12
    12B,1,24
    12C,1,56
    12D,1,423
    12E,1,32
    12F,1,3
    Depends on the number of records in the second table,we need to append A to Z at the end of the name field. The number of records will not exceed more than 26. How we can achieve this?
    Thanks
    Pandeeswaran

    OK, now you give another useful information - that there always will be combinations of sums in table2 to match the values in table1. (It is difficult to help when you tell the specs one at a time :-) )
    But it is not easy, because the code really will have to try and consider all possible combinations and then "choosing the right one" - this is easy for us humans, but not easy to encode in programming logic.
    I have made an attempt:
    SQL> set linesize 120
    SQL> with table1 as (
      2     select 'A1' name, 123 id, 150 value from dual union all
      3     select 'A2' name, 123 id, 200 value from dual union all
      4     select 'A3' name, 123 id, 300 value from dual
      5  ), table2 as (
      6     select 123 id, 100 value from dual union all
      7     select 123 id, 100 value from dual union all
      8     select 123 id, 50  value from dual union all
      9     select 123 id, 100 value from dual union all
    10     select 123 id, 100 value from dual union all
    11     select 123 id, 100 value from dual union all
    12     select 123 id, 100 value from dual
    13  )
    14  --
    15  -- End of test data
    16  --
    17  select
    18  t1.id, t1.name, t1.value, t2.value,
    19  t1.rn, t1.minval, t1.maxval,
    20  t2.rn, t2.sumval
    21  from (
    22     select
    23     tab1.*,
    24     nvl(sum(tab1.value) over (
    25        partition by tab1.id
    26        order by tab1.rn
    27        rows between unbounded preceding and 1 preceding
    28     ),0) minval,
    29     sum(tab1.value) over (
    30        partition by tab1.id
    31        order by tab1.rn
    32        rows between unbounded preceding and current row
    33     ) maxval
    34     from (
    35        select
    36        table1.*,
    37        row_number() over (
    38           partition by table1.id
    39           order by table1.value desc
    40        ) rn
    41        from table1
    42     ) tab1
    43  ) t1
    44  join (
    45     select
    46     tab2.*,
    47     sum(tab2.value) over (
    48        partition by tab2.id
    49        order by tab2.rn
    50     ) sumval
    51     from (
    52        select
    53        table2.*,
    54        row_number() over (
    55           partition by table2.id
    56           order by table2.value desc
    57        ) rn
    58        from table2
    59     ) tab2
    60  ) t2
    61  on (t2.id = t1.id)
    62  where t2.sumval > t1.minval
    63  and t2.sumval <= t1.maxval
    64  order by
    65  t1.id,
    66  t1.rn,
    67  t2.rn
    68  ;
            ID NA      VALUE      VALUE         RN     MINVAL     MAXVAL         RN     SUMVAL
           123 A3        300        100          1          0        300          1        100
           123 A3        300        100          1          0        300          2        200
           123 A3        300        100          1          0        300          3        300
           123 A2        200        100          2        300        500          4        400
           123 A2        200        100          2        300        500          5        500
           123 A1        150        100          3        500        650          6        600
           123 A1        150         50          3        500        650          7        650
    7 rows selected.It does seem to work for your data sample, but it is much too simple a rule to work in general. My "rule" simply is to order the data by value descending and summing up until "enough" values have been added.
    Consider this data sample instead:
    SQL> with table1 as (
      2     select 'A1' name, 1 id, 100 value from dual union all
      3     select 'A2' name, 1 id, 200 value from dual union all
      4     select 'A3' name, 1 id, 300 value from dual union all
      5     select 'B1' name, 2 id, 100 value from dual union all
      6     select 'B2' name, 2 id, 200 value from dual
      7  ), table2 as (
      8     select 1 id, 25  value from dual union all
      9     select 1 id, 75  value from dual union all
    10     select 1 id, 50  value from dual union all
    11     select 1 id, 50  value from dual union all
    12     select 1 id, 175 value from dual union all
    13     select 1 id, 225 value from dual union all
    14     select 2 id, 25  value from dual union all
    15     select 2 id, 50  value from dual union all
    16     select 2 id, 75  value from dual union all
    17     select 2 id, 100 value from dual union all
    18     select 2 id, 50  value from dual
    19  )
    20  --
    21  -- End of test data
    22  --
    23  select
    24  t1.id, t1.name, t1.value, t2.value,
    25  t1.rn, t1.minval, t1.maxval,
    26  t2.rn, t2.sumval
    27  from (
    28     select
    29     tab1.*,
    30     nvl(sum(tab1.value) over (
    31        partition by tab1.id
    32        order by tab1.rn
    33        rows between unbounded preceding and 1 preceding
    34     ),0) minval,
    35     sum(tab1.value) over (
    36        partition by tab1.id
    37        order by tab1.rn
    38        rows between unbounded preceding and current row
    39     ) maxval
    40     from (
    41        select
    42        table1.*,
    43        row_number() over (
    44           partition by table1.id
    45           order by table1.value desc
    46        ) rn
    47        from table1
    48     ) tab1
    49  ) t1
    50  join (
    51     select
    52     tab2.*,
    53     sum(tab2.value) over (
    54        partition by tab2.id
    55        order by tab2.rn
    56     ) sumval
    57     from (
    58        select
    59        table2.*,
    60        row_number() over (
    61           partition by table2.id
    62           order by table2.value desc
    63        ) rn
    64        from table2
    65     ) tab2
    66  ) t2
    67  on (t2.id = t1.id)
    68  where t2.sumval > t1.minval
    69  and t2.sumval <= t1.maxval
    70  order by
    71  t1.id,
    72  t1.rn,
    73  t2.rn
    74  ;
            ID NA      VALUE      VALUE         RN     MINVAL     MAXVAL         RN     SUMVAL
             1 A3        300        225          1          0        300          1        225
             1 A2        200        175          2        300        500          2        400
             1 A2        200         75          2        300        500          3        475
             1 A1        100         50          3        500        600          4        525
             1 A1        100         50          3        500        600          5        575
             1 A1        100         25          3        500        600          6        600
             2 B2        200        100          1          0        200          1        100
             2 B2        200         75          1          0        200          2        175
             2 B1        100         50          2        200        300          3        225
             2 B1        100         50          2        200        300          4        275
             2 B1        100         25          2        200        300          5        300
    11 rows selected.In this dataset the simple ordering by value will not work - It should have been A3: (225,75), A2: (175,25) and A1: (50,50).
    I cannot really think of a reasonably simple way to do it in SQL alone. Maybe using the MODEL clause would be possible, but not trivial. It is possible it would be easier to solve this in PL/SQL by iterating through a couple of arrays and intelligently trying the different combinations, rather than brute-force creating all combinations in a huge piece of SQL.
    I am sorry, Pandeesh, but I can not think of a solution easily.
    I might be able to do something if I fiddled with the problem for a couple of days, but that would be beyond the scope of this forum. That would be a consulting job rather than a bit of forum help :-)

  • Need help in join

    hi,
    Following are my columns data in same table,
    Value1 Value2
    1 1
    2 2
    3 4
    1 3
    My output sould be as like follows
    value
    1
    2
    3
    4
    so please help me on this logc by proving sample query

    Hey or in other way i will explain my requirment,
    i have two reslutset,
    result set A and result set b. i want to join both the result set and bring the output as follows.
    resultA
    1
    2
    3
    1
    resultB
    1
    2
    3
    4
    ned to join these two results and bring the out put as follows
    result:
    1
    2
    3
    4
    i given my requirement in last post bit wrongly, the above requirement is correct. can u pls help me now

  • Need help on join query

    Hi All,
    Please help me on the below join condition,
    >SELECT * FROM ESTIMATE_LINE WHERE JOB_ID = '214582' AND ESTIMATE_ID = 2;
    Output : Returns 1 row,
    >SELECT * FROM ESTIMATE_ACCOUNTING_LINE WHERE JOB_ID = '214582' AND ESTIMATE_ID = 2;
    Output : Returns 3 rows,
    I would like to add these two outputs as on, Finally i've to get 4 rows in the output,
    For that am writing the query like this,
    SELECT EL.*,EAL.*
    FROM ESTIMATE_LINE EL,
    ESTIMATE_ACCOUNTING_LINE EAL
    WHERE EL.JOB_ID = EAL.JOB_ID (+)
    AND EL.ESTIMATE_ID = EAL.ESTIMATE_ID (+)
    AND EAL.JOB_ID = '214582'
    AND EL.ESTIMATE_ID = 2,
    It is not giving the exact output, the common fields are there in the join condition,
    Can some one please re write the query for expected output..
    I am trying it but not getting the exact output,Unable to find out where the mistake is ...
    Thanks,
    gra

    Hi,
    First, let me make sure I undersatnd the problem.
    You have a query that lookas for information about a given job_id and estimate_id the estimate_line table. This query produces X rows.
    You have another query that lookas for information about the same job_id and estimate_id the estimate_accounting__line table. This query produces Y rows.
    You want to get the same results in one query that produces X+Y rows.
    That sounds like a job for UNION, not a join.
    If the two queries produces the same number of columns, and the data types of the columns are similiar, then you can just write the two queries together. Instead of a semicolon at the end of the first query, you'll say UNION (or UNION ALL):
    SELECT * FROM ESTIMATE_LINE            WHERE JOB_ID = '214582' AND ESTIMATE_ID = 2
    UNION ALL
    SELECT * FROM ESTIMATE_ACCOUNTING_LINE WHERE JOB_ID = '214582' AND ESTIMATE_ID = 2;If the columns are not the same, you'll need to call some conversion functions, or add literal columns (such as NULL) to the queries.
    If you need help, post a little sampe data (CREATE TABLE and INSERT statements) and the results you want from that data.

  • Help with join query

    Hi,
    I was wondering if someone could help me out with a join question
    I have threetables, phase, project and projectPhase. Primary keys in bold, foreign in italiz, foreign and primary in bold.italic:
    project
    projectCode
    phase
    phaseCode
    projectPhase
    projectCode
    phaseCode
    I was wondering is there a way to query to see, for a given project code, what phases that project has not got information for? I think I need an outer join for this but I'm not sure
    Thanks!

    i agree with you Jens thanks for spotting that i might have overlooked.
    try using Jens solution and it produce the result that you want. all you had to do is if the values are in different upper and lower case wrap it with either UPPER or LOWER function.
    SQL> select * from project;
    PROJECTCOD
    NNUU
    MKKU
    SQL> select * from phase;
    PHASECODE
    Req
    Des
    Plan
    SQL> select * from projectphase;
    PROJECTCOD PHASECODE
    NNUU       REQ
    NNUU       Des
    SQL> select Upper(phaseCode) phaseCode
      2    from phase
      3   minus
      4  select Upper(phaseCode) phaseCode
      5    from projectPhase
      6   where projectcode= 'NNUU';
    PHASECODE
    PLAN
    SQL>

  • Help! Add Result into JTree or JList.

    Hi,
    I retrived some values from one of the table from database using ResultSet. And I want to add
    the result into the JList or JTree. Any help will be greatly appreciated.
    Thanks in advance
    Sam.
    Here is the code.
    void searchButton_actionPerformed(ActionEvent e) {
    try{
    String query = "SELECT * FROM PINFO WHERE POLICYNUMBER = '" +
    searchTextfield.getText().toUpperCase() + "'";
    ResultSet rs = Application1.stmt.executeQuery(query);
    while(rs.next()){
    pid = (rs.getInt("PID"));
    System.out.println(pid);
    catch(SQLException ex){
    System.err.println("SQLException: " + ex.getMessage());
    try{
    String query = "SELECT * FROM (UNMATCH U LEFT JOIN DOCUMENTTYPE D ON U.DOCUMENTTYPE=D.DOCNUMBER) WHERE PID = '" + pid + "'";
    ResultSet rs1 = Application1.stmt.executeQuery(query);
    while (rs1.next()){
    String documentcode = (rs1.getString("DOCUMENTCODE"));
    //************** I want to add these documentcode into the Jlist or jTree.
    System.out.println(documentcode);
    catch(SQLException s){
    System.err.println("SQLException: " + s.getMessage());
    }

    public class blah
    Vector v;
    JList j;
    public blah()
    v = new Vector();
    j = new JList(v);
    JPanel jP = new JPanel();
    jP.add(j);
    public getResults()
    v.removeAllElements();
    j.setListData(v);
    String query......
    Resultset rs = .....
    while(rs.next())
    String s = rs.getString("");
    v.add(s);
    j.setListData(v);

  • Urgent Help Needed - Joining On Columns with Concatenated Values

    I have a challenging issue where I'm trying to join two tables together with a USER_ID column. The caveat is that in one of the tables, the USER_ID is potentially concatenated.
    For example, TABLE1 has 2 columns:
    1) USER ID
    2) USER NAME
    TABLE2 has 3 columns:
    1) USER ID
    2) USER COUNTRY
    3) USER DATE HIRED
    The resulting SQL query is:
    select * from TABLE1, TABLE2
    where TABLE1.USER_ID = TABLE2.USER_ID
    The problem is that TABLE1.USER_ID is only limited to 1 ID per record. However, TABLE2 potentially has concatenated USER ID's.
    In other words, while TABLE1 has a USER_ID = 'ABC123', that same ID may appear in TABLE2 concatenated as USER_ID = 'ABC123;ABC124'
    Obviously, with a natural join, this individual will be dropped from the SQL result-set.
    Is there a "join function" that I can use to say - "whenever I'm joining these 2 tables, as long as the TABLE1.USER_ID appears *ANYWHERE* in the TABLE2.USER_ID concatenated string (regardless of position), then please include this record in the join??
    As of right now, I have total 80 rows. 55 of them successfully are pulled because they have a one-to-one USER_ID correspondence. The other 25 are dropped out because they have multiple concatenated ID's in TABLE2 and only one ID in TABLE1.
    Any advice/help will be greatly appreciated!

    Hi
    Etbin wrote:
    Maybe
    select *
    from TABLE1,TABLE2
    where instr(TABLE2.USER_ID,TABLE1.USER_ID) > 0Regards
    Etbin
    Edited by: Etbin on 20.4.2012 23:27
    Forgot to mention; <strike>Urgent</strike>How could you forget the "I found love in Slovenia" problem?
    If the keys can be different lengths, then the solution above will match different keys if the one in table1 happens to be a substring of the one in table2. For example, if table1.userid='ABC'1, and table2.userid='ABC123;ABC124', then it will be considered a match.
    To avoid that:SELECT  *
    FROM      table1
    ,     table2
    WHERE      INSTR ( ';' || table2.user_id || ';'
               , ';' || table1.user_id || ';'
               ) > 0And Martijn is right (as usual). Storing several different values in a single column, like you're doing with table2.user_id, will cause lots of problems. Store each one in a separate row of a new table.

Maybe you are looking for

  • IOS 7 on iPhone 5 classic -- Battery Issues?

    I might as well start this since somebody inevitably will. I am niticing in the first hours after updating to iOS 7 that the battery seems to be draining faster than normal.  However I don't want to start a panic, because somebody says this about eve

  • Good news: We won't have to put up with the poor i...

    http://thenextweb.com/uk/2011/08/08/the-bbc-launches-a-new-tv-friendly-version-of-iplayer/ It actually looks really good, check out the video. BTW: Yes, it does say HD in the images but there is no mention in the article or on the video.

  • Digital certificates and keystore

    I have implemented the digital signature in my project. For that i have to add all the certificates in jre/lib/security/cacerts. Is it possible to store these certificates in database instead of keystore file (cacerts) ? if yes how to implement ? any

  • LJ1300 won't print multiple copies

    Just changed my desktop base unit and now running Windows 7.  My LJ1300 refuses to print more than 1 copy of any document.  I've removed the printer in "Devices and Printers", unplugged the USB and reconnected it, allowing it to reinstall itself, whi

  • Tecra A11 - Cannot get the FN buttons to work on Win 7

    I had to do a new install of Windows 7 on my Tecra A11. Everything works fine but, I am finding that I really really miss the ability to turn the trackpad on and off and turn the wireless on and off. I'm guessing that the only way to do this would be