Command Query using UNION

Hello,
I may be barking up the wrong tree and asking this question in the wrong forum so please accept my apologies if this is the case.
I have access to a MYSql database through a ODBC connection and would like to create a report based on four tables (let's say A, B, C and D) where tables A & B hold biographical data and tables C & D  contain different attribute detail with identical column names (attrib_name and attrib_desc) that relate to A & B .
The report I would like to create will list records from both A and B along with corresponding records from C and D merged into two columns attrib_name and attrib_desc.
I have tried a couple of versions of a union query but I just cannot seem to get it to generate the correct output.
Any help would be much appreciated.
Thank you
Paul

hi Paul,
Command objects are written in syntax specific to the database that you're using, so you may be best off looking at mysql forums instead. plus you haven't really stated what the issue is that you experiencing.
given the above, here's a couple basic things about UNION syntax...
1 the number of fields selected must be the same
2 the corresponding fields should be in the same sequence
3 the types (e.g. date, integer) must match
4 in your SELECT statement use an AS 'name' for each field so that the field names match up in both sets in the query
you may also wish to use a UNION ALL instead of a UNION as UNION ALL will ensure that all records are brought back as opposed to UNION which does a check on a virtual record set to ensure that there's no duplicates...this in turn can cause performance to suffer a bit.

Similar Messages

  • Writing query using UNION Operator

    Question -
    (1)
    Write an SQL Statement to list the following items: Customer ID, Customer Name, number of invoices, sum of total for invoices. Ensure that all customers are returned in the result set.
    Answer for the above is written as below by one person. That seams to be correct. Is there another way of writing this same query.;
    select c.CUSTOMER_ID,c.NAME,i.cnt,i.s
    from gee_customer c,(select customer_id,count(*) as cnt, sum(TOTAL) as s
    from gee_invoice
    group by customer_id) i
    where c.CUSTOMER_ID = i.customer_id (+)
    (2)
    My other question is How to write the above answer (or what you sugest) using UNION operator ?
    Any ideas please
    Message was edited by:
    user483578

    In fact the outer join means you use the union of two result sets - usual join result
    and the rows from the outer table for which there is not any row in the inner table.
    SQL> select d.deptno, e.ename from emp e, dept d
      2  where d.deptno = e.deptno(+)
      3  order by 1,2
      4  /
        DEPTNO ENAME
            10 CLARK
            10 KING
            10 MILLER
            20 ADAMS
            20 FORD
            20 JONES
            20 SCOTT
            20 SMITH
            30 ALLEN
            30 BLAKE
            30 JAMES
            30 MARTIN
            30 TURNER
            30 WARD
            40
    15 rows selected.
    SQL> select d.deptno,e.ename from emp e, dept d
      2  where d.deptno = e.deptno
      3  union
      4  select deptno, null
      5  from dept d where not exists (select null from emp e where e.deptno = d.deptno)
      6  order by 1,2
      7  /
        DEPTNO ENAME
            10 CLARK
            10 KING
            10 MILLER
            20 ADAMS
            20 FORD
            20 JONES
            20 SCOTT
            20 SMITH
            30 ALLEN
            30 BLAKE
            30 JAMES
            30 MARTIN
            30 TURNER
            30 WARD
            40
    15 rows selected.In your example something like (NOT tested !)
    with i as (select customer_id,count(*) as cnt, sum(TOTAL) as s
    from gee_invoice group by customer_id)
    select c.CUSTOMER_ID,c.NAME,i.cnt,i.s
    from gee_customer c, i
    where c.CUSTOMER_ID = i.customer_id
    union
    select c.CUSTOMER_ID,c.NAME,null,null
    from gee_customer c
    where not exists (select null from i where c.CUSTOMER_ID = i.customer_id)
    Rgds.

  • Sql query using union

    hi
    i need the query to fetch the data ...
    i have two table
    1. plan
    2. voidplan
    each table has id uniquely, and each table has rep_id but it is not unique.
    i retrieved the data from both table using union. now i need the data for the rep who is in both table. i want to check union by id, and i need to retrieve the reps who is in both tables.
    my code is
    select "PLAN"."ID" as "ID",
         "PLAN"."REP_ID" as "REP_ID",
         "PLAN"."REGION" as "REGION",
         "PLAN"."LOB" as "LOB",
         "PLAN"."PLAN_HIERARCHY_CHANGE" as "PLAN_HIERARCHY_CHANGE"
    from     "PLAN" "PLAN" ,"VOIDPLAN" "VOIDPLAN" where "PLAN"."REP_ID" IN (SELECT REP_ID FROM VOIDPLAN)
    UNION
    SELECT "VOIDPLAN"."ID" as "ID",
         "VOIDPLAN"."REP_ID" as "REP_ID",
         "VOIDPLAN"."REGION" as "REGION",
         "VOIDPLAN"."LOB" as "LOB",
         "VOIDPLAN"."PLAN_HIERARCHY_CHANGE" as "PLAN_HIERARCHY_CHANGE"
    from     "VOIDPLAN" "VOIDPLAN"
    THIS QUERY GIVES ALL UNION RESULT, NUT IT DOES'T FILTER THE REP_ID, IT SHOWS ALL THE REP_ID, I NEED THE REPS WHO IS IN BOTH TABLES
    CAN ANYONE PLEASE TELL ME THE SOLUTION
    regards
    vally.s

    SQL> create table plan
      2  as
      3  select 1 id, 1111 rep_id, 'vally' rep_name from dual union all
      4  select 2, 2222, 'kavi' from dual union all
      5  select 3, 3333, 'shyam' from dual
      6  /
    Tabel is aangemaakt.
    SQL> create table voidplan
      2  as
      3  select 5 id, 1111 rep_id, 'vally' rep_name from dual union all
      4  select 6, 2222, 'kavi' from dual
      5  /
    Tabel is aangemaakt.
    SQL> select case x when 1 then p.id else v.id end id
      2       , p.rep_id
      3       , p.rep_name
      4    from plan p
      5       , voidplan v
      6       , (select 1 x from dual union select 2 from dual) x
      7   where p.rep_id = v.rep_id
      8   order by 1
      9  /
       ID REP_ID REP_N
        1   1111 vally
        2   2222 kavi
        5   1111 vally
        6   2222 kavi
    4 rijen zijn geselecteerd.Regards,
    Rob.

  • Select query-using Union All display duplicate records.

    Hello All Gurus-
    I am using Oracle 9.i
    When i use the following query to fetch the records based on BUILDNUMBERNAME and ASSIGNED_BUILD then i am getting duplicate records -
    select T1.ID FROM Defect T1,statedef T2,repoproject T3
    WHERE T1.STATE=T2.ID AND T1.repoproject = T3.dbid AND T3.name Like 'ABC' AND T1. ASSIGNED_BUILD like '1.4.5.6'
    Union All
    select T1.ID FROM Defect T1,statedef T2,repoproject T3
    WHERE T1.STATE=T2.ID AND T1.repoproject = T3.dbid AND T3.name Like 'ABC' AND T1.BUILDNUMBERNAME like '1.4.5.6'
    How can i use the order by on T1.ID ? When i use the Order by T1.ID then it throws some error.
    Kindly help me in this :(
    Thanks in advance.

    Sorry for not providing all of the details -
    I am using Toad tool to run the query.
    1-When i use the following query -
    Select T1.ID FROM Defect T1,statedef T2,repoproject T3
    WHERE T1.STATE=T2.ID AND T1.repoproject = T3.dbid AND T3.name Like 'ABC' AND T1. ASSIGNED_BUILD like '1.4.5.6' order by T1.ID
    Union All
    select T1.ID FROM Defect T1,statedef T2,repoproject T3
    WHERE T1.STATE=T2.ID AND T1.repoproject = T3.dbid AND T3.name Like 'ABC' AND T1.BUILDNUMBERNAME like '1.4.5.6' order by T1.ID
    ORA-00933: SQL command not properly ended.
    2-If i am not using the T1.ID and run the following query
    Select T1.ID FROM Defect T1,statedef T2,repoproject T3
    WHERE T1.STATE=T2.ID AND T1.repoproject = T3.dbid AND T3.name Like 'ABC' AND T1. ASSIGNED_BUILD like '1.4.5.6'
    Union All
    select T1.ID FROM Defect T1,statedef T2,repoproject T3
    WHERE T1.STATE=T2.ID AND T1.repoproject = T3.dbid AND T3.name Like 'ABC' AND T1.BUILDNUMBERNAME like '1.4.5.6'
    Then it is running fine but it is displaying the duplicate values like -
    00089646
    00087780
    00089148
    00090118
    00090410
    00088503
    00080985
    00084526
    00087108
    00087109
    00087117
    00088778
    00086714
    00079518
    00087780
    00089148
    00090392
    00090393
    00090395
    00090398
    00090401
    00090402
    00090403
    00090406
    00090408
    00088503
    00080985
    00084526
    00087108
    00087109
    00087117
    00088778
    00086714
    00079518

  • Query using Union All and CTEs is slow

    TypePatient
    [ednum] int NOT NULL,  PK
    [BackgroundID] int NOT NULL, FK
    [Patient_No] varchar(50) NULL, FK
    [Last_Name] varchar(30) NULL,
    [First_Name] varchar(30) NULL,
    [ADateTime] datetime NULL,
    Treat
    [ID] int NOT NULL, PK
    [Ednum] numeric(10, 0) NOT NULL, FK
    [Doctor] char(50) NULL,
    [Dr_ID] numeric(10, 0) NULL,
    background
    [ID] int NOT NULL, PK
    [Patient_No] varchar(50) NULL, FK
    [Last_Name] char(30) NULL,
    [First_Name] char(30) NULL,
    [DateofBirth] datetime NULL,
    pdiagnose
    [ID] int NOT NULL, PK
    [Ednum] int NOT NULL, FK
    [DSMNo] char(10) NULL,
    [DSMNoIndex] char(5) NULL,
    substance
    [ID] int NOT NULL, PK
    [Ednum] int NOT NULL, FK
    [Substance] varchar(120) NULL,
    DXCAT
    [id] int NULL, PK
    [dx_description] char(100) NULL,
    [dx_code] char(10) NULL,
    [dx_category_description] char(100) NULL,
    [diagnosis_category_code] char(10) NULL)
    Substance
    ID
    Ednum
    Substance
    1
    100
    Alcohol Dependence
    4
    200
    Caffeine Dependence
    5
    210
    Cigarettes
    dxcat
    id
    dx_description
    dx_code
    dx_category_description
    diagnosis_category_code
    10
    Tipsy
    zzz
    Alcohol
    SA
    20
    Mellow
    ppp
    Mary Jane
    SA
    30
    Spacey
    fff
    LSD
    SA
    50
    Smoker
    ggg
    Nicotine
    SA
    pdiagnose
    ID
    Ednum
    DSMNo
    Diagnosis
    1
    100
    zzz
    Alcohol
    2
    100
    ddd
    Caffeine
    3
    210
    ggg
    Smoker
    4
    130
    ppp
    Mary Jane
    TypePatient
    ednum
    Patient_No
    Last_Name
    First_Name
    ADateTime
    100
    sssstttt
    Wolly
    Polly
    12/4/2013
    130
    rrrrqqqq
    Jolly
    Molly
    12/8/2013
    200
    bbbbcccc
    Wop
    Doo
    12/12/2013
    210
    vvvvwww
    Jazz
    Razz
    12/14/2013
    Treat
    ID
    Ednum
    Doctor
    Dr_ID
    2500
    100
    Welby, Marcus
    1000
    2550
    200
    Welby, Marcus
    1000
    3000
    210
    Welby, Marcus
    1000
    3050
    130
    Welby, Marcus
    1000
    background
    ID
    Patient_No
    Last_Name
    First_Name
    DateofBirth
    2
    sssstttt
    Wolly
    Polly
    8/6/1974
    3
    rrrrqqqq
    Jolly
    Molly
    3/10/1987
    5
    bbbbcccc
    Wop
    Doo
    8/12/1957
    6
    vvvvwww
    Jazz
    Razz
    7/16/1995
    Desired output:
    Staff ID
    Doctor
    Patient_No
    Client Name
    Date of Service
    Ednum
    DX Code
    DX Cat
    DX Desc
    Substance
    1000
    Welby, Marcus
    bbbcccc
    Wop, Doo
    12/12/2013
    200
    Caffeine Dependence
    1000
    Welby, Marcus
    rrrqqq
    Jolly, Molly
    12/8/2013
    130
    ppp
    SA
    Mary Jane
    1000
    Welby, Marcus
    sssttt
    Wolly, Polly
    12/4/2013
    100
    zzz
    SA
    Alcohol
    1000
    Welby, Marcus
    sssttt
    Wolly, Polly
    12/4/2013
    100
    ddd
    SA
    LSD
    1000
    Welby, Marcus
    sssttt
    Wolly, Polly
    12/4/2013
    100
    Alcohol Dependence
    1000
    Welby, Marcus
    vvvvwww
    Jazz, Razz
    12/14/2013
    210
    ggg
    SA
    Smoker
    1000
    Welby, Marcus
    vvvvwww
    Jazz, Razz
    12/14/2013
    210
    Cigarettes
    A patient is assigned an ednum. There are two different menus for staff to enter
    diagnoses. Each menu stores the entries in a different table. The two tables are substance and pdiagnose. A patient’s diagnosis for a substance abuse can be entered in one table and not the other. 
    The number of entries for different substances for each patient can vary between the two tables. John Doe might be entered for alcohol and caffeine abuse in the pdiagnosis table and entered only for caffeine abuse in the substance table. They are only
    linked by the ednum which has nothing to do with the diagnosis/substance. The substance entered in one table is not linked to the substance entered in the other. A query will not put an entry for alcohol from the pdiagnosis table on the same row as an alcohol
    entry from the substance table except by chance. That is the reason for the way the query is written.
    The query accepts parameters for a Dr ID and a start and end date. It takes about 7 to 15 seconds to run. Hard coding the dates cuts it down to about a second.
    I might be able to select directly from the union all query instead of having it separate. But then I’m not sure about the order by clauses using aliases.
    Is there a way to rewrite the query to speed it up?
    I did not design the tables or come up with the process of entering diagnoses. It can’t be changed at this time.
    Please let me know if you notice any inconsistencies between the DDLs, data, and output. I did a lot of editing.
    Thanks for any suggestions.
    with cte_dxcat (Dr_ID, Doctor, Patient_No,Last_Name,
    First_Name, Adatetime,Ednum,
    dx_code,diagnosis_category_code,dx_description,substance,
    DateofBirth) as
    (Select distinct t.Dr_ID, t.Doctor, TP.Patient_No,TP.Last_Name,
    TP.First_Name, TP.Adatetime as 'Date of Service',TP.Ednum,
    DXCAT.dx_code,DXCAT.diagnosis_category_code,DXCAT.dx_description,
    null as 'substance',BG.DateofBirth
    From TypePatient TP
    inner join treat t on TP.ednum = t.Ednum
    inner join background BG on BG.Patient_No = TP.Patient_No
    inner join pdiagnose PD on TP.Ednum = PD.Ednum
    inner join Live_Knowledge.dbo.VA_DX_CAT_MAPPING DXCAT on DXCAT.dx_code = PD.DSMNo
    Where (TP.Adatetime >= convert(varchar(10), :ST, 121)+ ' 00:00:00.000'
    and TP.Adatetime <= convert(varchar(10), :SP, 121)+ ' 23:59:59.000')
    and DXCAT.diagnosis_category_code = 'SA'
    and t.Dr_ID =:DBLookupComboBox2
    cte_substance (Dr_ID, Doctor, Patient_No,Last_Name,
    First_Name,Adatetime, Ednum,
    dx_code,diagnosis_category_code,dx_description,Substance,DateofBirth) as
    (Select distinct t.Dr_ID, t.Doctor, TP.Patient_No,TP.Last_Name,
    TP.First_Name, TP.Adatetime as 'Date of Service', TP.Ednum,
    null as 'dx_code',null as 'diagnosis_category_code',null as 'dx_description',s.Substance, BG.DateofBirth
    From TypePatient TP
    inner join treat t on TP.ednum = t.Ednum
    inner join background BG on BG.Patient_No = TP.Patient_No
    inner join pdiagnose PD on TP.Ednum = PD.Ednum
    inner join substance s on TP.Ednum = s.Ednum
    Where (TP.Adatetime >= convert(varchar(10), '12/1/2013', 121)+ ' 00:00:00.000'
    and TP.Adatetime <= convert(varchar(10), '12/31/2013', 121)+ ' 23:59:59.000')
    and t.Dr_ID =:DBLookupComboBox2
    cte_all (Dr_ID, Doctor, Patient_No,Last_Name,
    First_Name,Adatetime, Ednum,
    dx_code,diagnosis_category_code,dx_description,Substance,DateofBirth) as
    (select cte_dxcat.Dr_ID as 'Staff ID', cte_dxcat.Doctor as 'Doctor',
    cte_dxcat.Patient_No as 'Patient_No',
    cte_dxcat.Last_Name as 'Last',cte_dxcat.First_Name as 'First',
    cte_dxcat.Adatetime as 'Date of Service',cte_dxcat.Ednum as 'Ednum',
    cte_dxcat.dx_code as 'DX Code',cte_dxcat.diagnosis_category_code as 'DX Category Code',
    cte_dxcat.dx_description as 'DX Description',
    cte_dxcat.substance as 'Substance',cte_dxcat.DateofBirth as 'DOB'
    from cte_dxcat
    union all
    select cte_substance.Dr_ID as 'Staff ID', cte_substance.Doctor as 'Doctor',
    cte_substance.Patient_No as 'Patient_No',
    cte_substance.Last_Name as 'Last',cte_substance.First_Name as 'First',
    cte_substance.Adatetime as 'Date of Service',cte_substance.Ednum as 'Ednum',
    cte_substance.dx_code as 'DX Code',cte_substance.diagnosis_category_code as 'DX Category Code',
    cte_substance.dx_description as 'DX Description',
    cte_substance.substance as 'Substance',cte_substance.DateofBirth as 'DOB'
    from cte_substance)
    select cte_all.Dr_ID as 'Staff ID', cte_all.Doctor as 'Doctor',
    cte_all.Patient_No as 'Patient_No',
    (cte_all.Last_Name + ', '+ cte_all.First_Name) as 'Client Name',
    cte_all.Adatetime as 'Date of Service',cte_all.Ednum as 'Ednum',
    cte_all.dx_code as 'DX Code',cte_all.diagnosis_category_code as 'DX Category Code',
    cte_all.dx_description as 'DX Description',
    cte_all.substance as 'Substance',
    CONVERT(char(10), cte_all.DateofBirth,101) as 'DOB'
    from cte_all
    order by cte_all.Patient_No,cte_all.Adatetime

    Please post real DDL instead of your invented non-language, 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. Your rude, non-SQL narrative is so far away from standards I cannot even use you as a bad example in book. 
    Temporal data should use ISO-8601 formats (we have to re-type the dialect you used!). Code should be in Standard SQL as much as possible and not local dialecT. 
    This is minimal polite behavior on SQL forums. You posted a total mess! Do you really have patients without names?? You really use a zero to fifty characters for a patient_nbr??? Give me an example. That is insane! 
    Your disaster has more NULLs than entire major corporate systems. Since you cannot change it, can you quit? I am serious. I have been employed in IT since 1965, and can see a meltdown.
    I looked at this and I am  not even going to try to help you; it is not worth it. I am sorry for you; you are in an environment where you cannot learn to do any right. 
    But you are still responsible for the rudeness of not posting DDL. 
    --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

  • Returning a count from a query using Union

    Hi. I'm attempting to select a count from this query and then display the total in a message, but I'm getting a 'Too many rows returned' (ORA-01422). Can anyone tell me how I can achieve a total for this query?
             SELECT nvl(count(*),0)
           INTO conflict_cnt
           FROM dropper_assign
           WHERE dropper_id = :dropper_vacations.dropper_id AND
                trunc(sched_date) between :begin_dt and :end_dt
              union                          
       SELECT nvl(count(*),0)
        FROM exfc.bundle a, splits b
        WHERE a.bundle = b.bundle AND
             b.dropper_id = :dropper_vacations.dropper_id AND
             trunc(a.actual_dt) between :begin_dt and :end_dt;
              call_alert.the_error('test: '||to_char(conflict_cnt));Any help would be greatly appreciated.

    Thanks Christian, I can know return to my favourite present occupation named HOLIDAYS ;)
    btw with count function as the first message
    WITH
      data AS
        SELECT
          COUNT(*) cnt
        FROM
          dual
          CONNECT BY level <= 10
        UNION
        SELECT
          COUNT(*) cnt
        FROM
          dual
          CONNECT BY level <= 20
    SELECT
      SUM(cnt)
    FROM
      data
    SUM(CNT)              
    30        
    /* and */
    WITH
      data AS
        SELECT
          COUNT(*) cnt
        FROM
          dual
          CONNECT BY level <= 10
        UNION ALL /****** returns me also 30 *****/
        SELECT
          COUNT(*) cnt
        FROM
          dual
          CONNECT BY level <= 20
    SELECT
      SUM(cnt)
    FROM
      data
    SUM(CNT)              
    30       result will defer only if both count return exactly the same value so definitely UNION ALL for that case or the simple solution I have provided before ...
    but leave it. that's enough messages for this thread ;)
    Jean-Yves
    Edited by: JeanYves Bernier on 9 août 2011 17:42

  • Need column showing 'Y' or 'N' values in query using Union

    Hello Folks,
    My 1st table is customer table with name, lastname, age, party id , custom id
    2nd table is department table with party id , dupeflag
    3rd table is sales table with custom id , indicator
    I need to combine them and get a new column which has certain conditions.
    Requirement:
    Need name, lastname, age, party id , custom id , NewIndicator
    and below conditions should be folllowed.
    dupe flag indiactaor flag New Colum to have (say NewIndicator)
    0,1,2 Y Y
    3 Y N
    0,1,2 N N
    3 N N
    I need to do a union to get all the values
    select a.party_id from customer a join department b
    on a.party_id=b.party_id
    UNION ALL
    select a.custom_id from customer c join sales d
    on c.custom_id=d.custom_id
    But now how do i build the case statement to fulfil my new column setting conditions.. I'm confused with case statemnent..
    Please help ASAP..
    Thanks..

    How do I ask a question on the forums?
    SQL and PL/SQL FAQ

  • Alert Drill Down - DRAFT and ADDED Documnts - Using UNION Query

    Hi,
    I want to be able to send and alert that allows drill down when the alert includes DRAFT and ADDED doc's
    My alert query uses UNIONs for the draft table  and ADDED type documents, selecting a dummy draft number for ADDED doc.
    --EXTRACT
    select
    --For DRAFTs
    T0.DocEntry   as 'Draft_No',
    ''               as  'Doc_No',
    'Draft'       as 'Type', ---etc. etc.
    From ODRF 
    UNION
    ---For  ADDED
    select
    (select min(docentry) from ODRF) as 'Draft_No',
    T0.Docnum  as  'Doc_No',
    'ADDED'       as 'Type', -
    etc etc
    From ORDR
    Sample :DRAFT = 2 is dummy
    Draft_No Doc_No   Type     Draft Status Cust/Vend   Doc_Type             Line Type      Approval_Status
    2              121095   ADDED   N/A             NPO-PORT      Sales Order            Item                Approved
    811           0            Draft       Open          ADT               AP Invoice           Service        Approved     
    Thanks you for any help on this issue.
    Eric

    Hi Eric,
    This is impossible.  Simply because, once you are using Union, drill down will no longer work.
    Thanks,
    Gordon

  • Query takes long when using UNION

    Hi ,
    I habe a query as follows;
    SELECT
                        '9999' site_id,
                        m.ghi_prov_num provnum,
                           SUBSTR (l.seq_num, 1, 3)provloc,
                        t.dea_number dea,
                            t.license_number statelicensenumber ,
                            n.npi_num npi,
                            m.prefix prefixname,
                            m.lastname lastname,
                            m.firstname firstname,
                            t.middle_name middleinitial,
                            m.suffix suffixname,
                            null clinicname,
                            l.street1 addressline1,
                            l.street2 addressline2,
                            l.city city,
                            l.state state,
                            l.zip5 zip,
                            l.phone phoneprimary,
                            null ext,
                            null fax,
                            null email,
                            null alt_phone,
                            null alt_phone_ext
                     FROM provider m, LOCATION l, npi n,TEMP_VITAL_CACTUS t,test_provider_pin pin
                      WHERE m.ghi_prov_num=l.ghi_prov_num
                          and m.ghi_prov_num=n.ghi_prov_num(+)
                          and m.ghi_prov_num=t.ghi_prov_num(+)
                          and m.tax_id=pin.tax_id
         UNION
          SELECT   
                        '9999', m.ghi_prov_num ,
                            m.location provloc,
                           null  ,
                           null  ,
                            n.npi_num  ,
                            null ,
                            m.lastname ,
                            m.firstname  ,
                            null,
                            null  ,
                            null  ,
                            m.street1  ,
                            m.street2  ,
                            m.city ,
                            m.state  ,
                            m.zip5 ,
                            m.phone  ,
                            null  ,
                            null  ,
                            null  ,
                            null  ,
                            null
                           FROM dental_provider m, npi n,test_provider_pin pin
                       WHERE m.ghi_prov_num=n.tax_id(+)
                           and m.location=n.location(+)
                            and pin.tax_id=m.ghi_prov_num;The query takes for ever;
    But Individual query takes less than a sec to execute.Is there any way can i rewrite the query?
    Please help
    Hena.

    user11253970 wrote:
    But Individual query takes less than a sec to execute.Is there any way can i rewrite the query?Have a feeling you are using Toad/SQL Navigator or similar tool which returns data one screen at a time. If so, then it does not "takes less than a sec to execute" but rather to fetch first screen of rows. When you use UNION Oracle has to return distinct rows from both queries. Therefore it must fetch not just first screen but all rows. To verify, issue first query and in yiour GUI tool click on get last screen. Then you'll know how long whole select takes. Do the same for second query. Also, do you need distinct rows or akll rows? IF all rows, change UNION to UNION ALL.
    SY.

  • Cannot export query output when using UNION ALL

    Hi
    I can run a query in SQL Developer 1.5.5 and if it's a SELECT statement it works fine, but if I output the result of several SELECT statements using UNION ALL after some 10,000 records the SQL Developer crashes and it generates a file whose size is 0 kb
    Is there a workaround for this??
    Thanks and Regards!
    Isaac

    Should be fixed in the upcoming 2.1... you can try the RC1 also...
    Regards,
    K.

  • SQL query error using Union

    Hello!
    I need some correction in the following query. I am trying to make a 2 page QPLD so I am joining 2 queries and then printing the report into 2 pages.
    SELECT T0.[U_OANumber], T0.[custmrName], T0.[U_Inspection], T0.[U_Cust_PO_Num],
    T0.[U_ModelType], T0.[U_Duty], T0.[U_NamePlate],
    T0.[U_Indicator_Obs], T0.[U_Fastners], T0.[U_Mounting_Type], T0.[U_Casing_Orientation], T0.[U_Impeller_Dia],
    T0.[U_Bearing_Style], T0.[U_Motor_HP_Size], T0.[U_InsulationWedges], T0.[U_Varnish], T0.[U_Paint_Shade],
    T0.[U_PlugsSeal], T0.[U_Remarks], T0.[U_Despatch]
    FROM OINS T0 WHERE T0.[U_OANumber] = '[%0]' or  T0.[customer] = '[%1]' or T0.[manufSN] = '[%2]'
    Union all
    SELECT T0.[U_ModelType], T0.[U_Size], T0.[U_Discharge], T0.[U_Head], T0.[U_RPM], T0.[U_YOM], T0.[U_HP],
    T0.[U_Amps], T0.[U_Insulation_Class], T0.[U_Winding_Connection]
    FROM OINS T0 WHERE
    T0.[U_OANumber] = '[%0]' or  T0.[customer] = '[%1]' or T0.[manufSN] = '[%2]'
    Do I have to use the where clause just once since it is identical to both statements?
    I get the error stating that all queries using Union, Intersect or Except must have an equal number of expressions. what does this mean?
    scorp
    Edited by: scorpion 666 on Feb 12, 2009 1:30 PM

    Union has to have exact same numbers of fields to combine two results.  Your query shows no need of union because your where clauses are identical.
    Right syntax would be like this:
    SELECT T0.[U_OANumber], T0.[custmrName], T0.[U_Inspection], T0.[U_Cust_PO_Num],
    T0.[U_ModelType], T0.[U_Duty], T0.[U_NamePlate],
    T0.[U_Indicator_Obs], T0.[U_Fastners], T0.[U_Mounting_Type], T0.[U_Casing_Orientation], T0.[U_Impeller_Dia],
    T0.[U_Bearing_Style], T0.[U_Motor_HP_Size], T0.[U_InsulationWedges], T0.[U_Varnish], T0.[U_Paint_Shade],
    T0.[U_PlugsSeal], T0.[U_Remarks], T0.[U_Despatch], T0.[U_Size], T0.[U_Discharge], T0.[U_Head], T0.[U_RPM], T0.[U_YOM], T0.[U_HP],
    T0.[U_Amps], T0.[U_Insulation_Class], T0.[U_Winding_Connection]
    FROM DBO.OINS T0 WHERE T0.[U_OANumber] = '[%0]' or  T0.[customer] = '[%1]' or T0.[manufSN] = '[%2]'
    Thanks,
    Gordon

  • Need sql query to remove duplicates using UNION ALL clause

    Hi,
    I have a sql query which has UNION clause.But the UNION clause is causing some performance issues.
    To overcome that I have used UNION ALL to improve performance but its returning duplicates.
    Kindly anyone send a sample SQL query where my primary objective is used to use UNION ALL clause and to consider unique rows (elimating duplicate
    ones)
    Any help will be needful for me
    Thanks and Regards

    why not UNION? :(
    another way also use MINUS
    SQL>
    SQL> with t as
      2  (
      3  select 1 if from dual union all
      4  select 2 if from dual union all
      5  select 1 if from dual union all
      6  select 3 if from dual union all
      7  select 3 if from dual
      8  )
      9  ,t2 as
    10  (
    11  select 1 if from dual union all
    12  select 2 if from dual union all
    13  select 3 if from dual union all
    14  select 4 if from dual union all
    15  select 5 if from dual
    16  )
    17  (select if from t
    18  union all
    19  select if from t2)
    20  /
            IF
             1
             2
             1
             3
             3
             1
             2
             3
             4
             5
    10 rows selected
    SQL> so
    SQL>
    SQL> with t as
      2  (
      3  select 1 if from dual union all
      4  select 2 if from dual union all
      5  select 1 if from dual union all
      6  select 3 if from dual union all
      7  select 3 if from dual
      8  )
      9  ,t2 as
    10  (
    11  select 1 if from dual union all
    12  select 2 if from dual union all
    13  select 3 if from dual union all
    14  select 4 if from dual union all
    15  select 5 if from dual
    16  )
    17  (select if from t
    18  union all
    19  select if from t2)
    20  minus
    21  select -99 from dual
    22  /
            IF
             1
             2
             3
             4
             5
    SQL>

  • Requirement is to run CMD.EXE under the Local System Account. So that we can map a network drive to be used by a windows service, which will be created by command: - net use z: \\servername\sharedfolder /persistent:yes

    Environment:
    OS:  Windows 7 32/64 bit, Windows 2008 Server 64
    bit/ Windows 2012 Server 64 bit
    Priority:
    - Critical
    Requirement: - Since
    the Windows Service is running under the Local System Account, we would like to emulate this same behaviour.
    Basically, we would like to run CMD.EXE under the Local System Account. So that we can map a network drive to be used by a service using following
    command
    net use z: \\servername\sharedfolder /persistent:yes.
    Already Attempt:
    We tried to launch the CMD.exe using the DOS Task Scheduler AT command.  Here’s a sample command:
    AT 10:36 /interactive cmd.exe
    But I received a warning that “due
    to security enhancements, this task will run at the time excepted but not interactively.”
    It turns out that this approach will work for XP, 2000 and Server 2003 but due to session isolation
    Interactive services no longer work on Windows 7, Windows Server 2008 and above.
      2.  We
    tried to create a secondary Windows Service via the Service Control (sc.exe) which merely launches CMD.exe.
    <Drive>:\sc create RunCMDAsLSA binpath= "cmd" type=own type=interact <Drive>:\sc
    start RunCMDAsLSA
    In this case the service fails to start and results it the following error message:
    FAILED 1053: The service did not respond to the start or control request in a timely fashion.
      3. One
    suggestion, we found to launch CMD.exe via a Scheduled Task, but
    it is not giving any option to launch CMD.exe in interactive mode; so that I can map network drive using net command.
      4. I read an article, which
    demonstrates the use of PSTools from SysInternals. I launched the command line and executed following command
    psexec -i -s cmd.exe
    PSTools worked fine, but It seems that in scope of Sysinternals Software License
    Terms. You may not "use the software for commercial software hosting services."
    Application will deploy on client, which will be like commercial,
    so we are not able to use PSTools.         
    Kindly assist us for achieving the requirement. We have tried all the ways, but nothing is working for us. Kindly suggest.
    I will be really thankful.

    Hi Sir,
    Nothing worked from above for us. You can see our remarks on posted query.
    That’s why, we posted on forum.
    And there will not be any vulnerability, because, if we will use "net
    use ..."
    in network domain; definitely,
    we will provide username and password of mapped drive system.
    And, that system, itself is given by client; so that, there must not be any vulnerability; they are ready to provide user name and password.
    We need a way; by which we can complete the requirement. Kindly assist.
    Regards,
    S. P. Singh

  • How can I perform this kind of range join query using DPL?

    How can I perform this kind of range join query using DPL?
    SELECT * from t where 1<=t.a<=2 and 3<=t.b<=5
    In this pdf : http://www.oracle.com/technology/products/berkeley-db/pdf/performing%20queries%20in%20oracle%20berkeley%20db%20java%20edition.pdf,
    It shows how to perform "Two equality-conditions query on a single primary database" just like SELECT * FROM tab WHERE col1 = A AND col2 = B using entity join class, but it does not give a solution about the range join query.

    I'm sorry, I think I've misled you. I suggested that you perform two queries and then take the intersection of the results. You could do this, but the solution to your query is much simpler. I'll correct my previous message.
    Your query is very simple to implement. You should perform the first part of query to get a cursor on the index for 'a' for the "1<=t.a<=2" part. Then simply iterate over that cursor, and process the entities where the "3<=t.b<=5" expression is true. You don't need a second index (on 'b') or another cursor.
    This is called "filtering" because you're iterating through entities that you obtain from one index, and selecting some entities for processing and discarding others. The white paper you mentioned has an example of filtering in combination with the use of an index.
    An alternative is to reverse the procedure above: use the index for 'b' to get a cursor for the "3<=t.b<=5" part of the query, then iterate and filter the results based on the "1<=t.a<=2" expression.
    If you're concerned about efficiency, you can choose the index (i.e., choose which of these two alternatives to implement) based on which part of the query you believe will return the smallest number of results. The less entities read, the faster the query.
    Contrary to what I said earlier, taking the intersection of two queries that are ANDed doesn't make sense -- filtering is the better solution. However, taking the union of two queries does make sense, when the queries are ORed. Sorry for the confusion.
    --mark                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Can a report be developed using free hand SQL(Sql Query) using a DB Link

    Hello All,
    A report to be developed based on query in OBIEE dashboards
    Select Query -----1
    UNION
    Select Query------2
    First select query is coming from one database schema and second is coming from the other.
    Is there any way to develop the report using free hand SQL based on a DB link?
    Is there any feature to use Database link (DB link)?
    Thank in Advance,
    SMA

    What you ask is the direct database request capabilities :
    http://gerardnico.com/wiki/dat/obiee/presentation_service/obiee_direct_database_request
    But you can also use the federated query capabilities of the repository to model a star schema with two star schema from two different data source.
    Cheers
    Nico

Maybe you are looking for