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.

Similar Messages

  • Creating table or View using UNION Operator ???????

    Hi all
    please need some help ,i have created aquery using UNION operator
    (i.e
    select A,to_number(null),C from table1
    Union
    select A,B,To_number(null) from table2)
    it gives the output correctly and i need to make this output as View ot table
    eacg time i use
    Create or replace view v_1 ...........
    it gives me this error :: unknown command "UNION" - rest of line ignored.
    can any one pls tell me what to do
    Thanks

    Hi,
    I found there is no error in your sql
    create view x_v
    as
    select a from x
    union
    select to_number(null) from y;
    this works fine.
    in your sql check your right or left peranthesis
    regards
    Ripudaman

  • How to write the given query using 'ANY ' operator

    Hi,
    How to write the given query using 'ANY ' operator , I dont need to fetch to grade_master table twice in database, just need to fetch within the result set.
    SELECT dsg_code,dsg_name,dsg_grade FROM designation_master WHERE dsg_orgn='&&Orgn' and dsg_ctry='&&ctry'
    And dsg_loc ='&&loc' And dsg_oru = '&&oru' and dsg_grade in decode('&&radio_group',
    1, SELECT grd_code FROM grade_master WHERE grd_osm_code in (Select grd_osm_code FROM grade_master WHERE grd_orgn='&&Orgn' and grd_ctry='&&ctry' And grd_loc ='&&loc' And grd_oru = '&&oru' and grd_code ='&&emp_grade'),
    2, SELECT grd_code FROM grade_master WHERE grd_osm_code > (Select grd_osm_code FROM grade_master WHERE grd_orgn='&&orgn' and grd_ctry='&&ctry' and grd_loc ='&&loc' And grd_oru = '&&oru' and grd_code),
    3, SELECT grd_code FROM grade_master WHERE grd_osm_code < (Select grd_osm_code FROM grade_master WHERE grd_orgn='&&orgn' and grd_ctry='&&ctry' And grd_loc ='&&loc' And grd_oru = '&&oru' and grd_code ='&&emp_grade'))
    thanks
    rincy

    Hi,
    One thing I understood my your issue is you want to perform, execution of query once or fetch the results sets my minimizing the number of times executions of queries. It would be hard for us to check in this way, atleast provide some temporary data and some business rules. Only I can IN, >, < (queries logical conditons on inner query)
    - Pavan Kumar N
    - ORACLE OCP - 9i/10g
    https://www.oracleinternals.blogspot.com

  • To re-write query using 'ANY' operator

    Hi,
    How to write the given query using 'ANY ' operator , I dont need to fetch to grade_master table twice in database, just need to fetch within the result set.
    SELECT dsg_code,dsg_name,dsg_grade FROM designation_master WHERE dsg_orgn='&&Orgn' and dsg_ctry='&&ctry'
    And dsg_loc ='&&loc' And dsg_oru = '&&oru' and dsg_grade in decode('&&radio_group',
    1, SELECT grd_code FROM grade_master WHERE grd_osm_code in (Select grd_osm_code FROM grade_master WHERE grd_orgn='&&Orgn' and grd_ctry='&&ctry' And grd_loc ='&&loc' And grd_oru = '&&oru' and grd_code ='&&emp_grade'),
    2, SELECT grd_code FROM grade_master WHERE grd_osm_code > (Select grd_osm_code FROM grade_master WHERE grd_orgn='&&orgn' and grd_ctry='&&ctry' and grd_loc ='&&loc' And grd_oru = '&&oru' and grd_code),
    3, SELECT grd_code FROM grade_master WHERE grd_osm_code < (Select grd_osm_code FROM grade_master WHERE grd_orgn='&&orgn' and grd_ctry='&&ctry' And grd_loc ='&&loc' And grd_oru = '&&oru' and grd_code ='&&emp_grade'))
    thanks
    rincy

    Tubby is correct that data and create statements are required to analyze it correctly.
    Still I worked on it and created something using WITH clause
    with grd_query
    as
    (Select grd_osm_code FROM grade_master WHERE grd_orgn='&&orgn' and grd_ctry='&&ctry' and grd_loc ='&&loc' And grd_oru = '&&oru' and grd_code ='&&emp_grade')
    ,grd_mst_query
    as
    (SELECT grd_code, grd_osm_code FROM grade_master)
    SELECT dsg_code, dsg_name, dsg_grade
      FROM designation_master
    WHERE dsg_orgn = '&&Orgn'
       AND dsg_ctry = '&&ctry'
       AND dsg_loc = '&&loc'
       AND dsg_oru = '&&oru'
       AND dsg_grade in   
       decode('&&radio_group',1, (SELECT grd_code FROM grd_mst_query WHERE grd_osm_code in (select * from grd_query)),
    2, (SELECT grd_code FROM grd_mst_query WHERE grd_osm_code > (select * from grd_query)),
    3, (SELECT grd_code FROM grd_mst_query WHERE grd_osm_code < (select * from grd_query)))this should avoid multiple scans on same table.
    thanks

  • Using union operator in discoverer

    Hi All,
    I have a sql statement which is to be implemented in discoverer:
    (select ........where user_entered_date='YYYY/MM/DD' )
    UNION
    (select ........where user_entered_date='YYYY/MM/DD'
    AND (select ........where user_entered_date='YYYY/MM/DD' ))
    Problem:
    a) There are nested select statements which require parameters to be entered by the user.
    b) How would I implement the union operator in the above scenario?
    I would really appreciate it if someone could give a work around.
    Regards,
    Nav

    Hi,
    Unfortunately, we can not have a SQL query with Union in Discoverer directly.
    You should create a view based on the complete query and then create folder using the view.
    You can provide a parameter at the report level.
    For eg :
    View query : select as_of_date from table_name
    Report : Add a paremeter for as_of_date
    Hope this Helps!
    Yogini

  • Select Query using AND operation

    Hello,
    I am developing RFC which will retrieve some records from SAP HR module table.
    Input will be one structure (INPUT_TABLE) containing 4 fields. User may enter values for any fields, and my requirement is to perform a AND operation on those entered fields only. Currently i am writing query as follows :
    SELECT DISTINCT apernr aVORNA aNACHN acname a~gbdat FROM
                  PA0002 as a INTO CORRESPONDING FIELDS OF TABLE Z_PD_TABLE
                                                WHERE apernr = INPUT_TABLE-pernr AND aVNAMC = INPUT_TABLE-VORNA AND aNCHMC = INPUT_TABLE-NACHN AND agbdat = INPUT_TABLE-GBDAT .
    If only 2 values are entered by user out of 4 , it will perform AND operation by taking other values as blank or 000000. I want to skip these AND operation on fields which are not entered by user.
    Please help for writing query.
    Thanks in advance,
    Prashant

    Hi,
    Create dynamic where condition based upon user input.
    Try like this....
    IF NOT INPUT_TABLE-pernr IS INITIAL.
          CLEAR : lv_pernr_condition.
          CONCATENATE 'PERNR' ' = ' '''' INPUT_TABLE-pernr ''''  INTO
          lv_pernr_condition.
    ENDIF.
    IF NOT INPUT_TABLE-vnamc IS INITIAL.
          CLEAR : lv_vnamc_condition.
          CONCATENATE 'VNAMC' ' = ' '''' INPUT_TABLE-vnamc ''''  INTO
          lv_vnamc_condition.
    ENDIF.
    IF NOT INPUT_TABLE-vorna IS INITIAL.
          CLEAR : lv_vorna_condition.
          CONCATENATE 'VORNA' ' = ' '''' INPUT_TABLE-vorna ''''  INTO
          lv_vorna_condition.
    ENDIF.
    IF NOT INPUT_TABLE-nchmc IS INITIAL.
          CLEAR : lv_nchmc_condition.
          CONCATENATE 'NCHMC' ' = ' '''' INPUT_TABLE-nchmc ''''  INTO
          lv_nchmc_condition.
    ENDIF.
    IF NOT INPUT_TABLE-gbdat IS INITIAL.
          CLEAR : lv_gbdat_condition.
          CONCATENATE 'GBDAT' ' = ' '''' INPUT_TABLE-gbdat ''''  INTO
          lv_gbdat_condition.
    ENDIF.
    IF NOT lv_pernr_condition IS INITIAL.
          CONCATENATE lv_pernr_condition lv_condition
          INTO lv_condition SEPARATED BY space.
    ENDIF.
    IF NOT lv_vnamc_condition IS INITIAL.
          IF lv_condition IS INITIAL.
            CONCATENATE lv_vnamc_condition lv_condition
                INTO lv_condition SEPARATED BY space.
          ELSE.
            CONCATENATE lv_condition 'AND' lv_vnamc_condition
                INTO lv_condition SEPARATED BY space.
          ENDIF.
    ENDIF.
    IF NOT lv_vorna_condition IS INITIAL.
          IF lv_condition IS INITIAL.
            CONCATENATE lv_vorna_condition lv_condition
                INTO lv_condition SEPARATED BY space.
          ELSE.
            CONCATENATE lv_condition 'AND' lv_vorna_condition
                INTO lv_condition SEPARATED BY space.
          ENDIF.
    ENDIF.
    IF NOT lv_nchmc_condition IS INITIAL.
          IF lv_condition IS INITIAL.
            CONCATENATE lv_nchmc_condition lv_condition
                INTO lv_condition SEPARATED BY space.
          ELSE.
            CONCATENATE lv_condition 'AND' lv_nchmc_condition
                INTO lv_condition SEPARATED BY space.
          ENDIF.
    ENDIF.
    IF NOT lv_gbdat_condition IS INITIAL.
          IF lv_condition IS INITIAL.
            CONCATENATE lv_gbdat_condition lv_condition
                INTO lv_condition SEPARATED BY space.
          ELSE.
            CONCATENATE lv_condition 'AND' lv_gbdat_condition
                INTO lv_condition SEPARATED BY space.
          ENDIF.
    ENDIF.
    SELECT DISTINCT pernr VORNA NACHN cname gbdat FROM
    PA0002 INTO CORRESPONDING FIELDS OF TABLE Z_PD_TABLE
    WHERE lv_condition .   " Dynamic where condition
    Hope it will helps

  • 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.

  • How to pass variable into lov sql query using like operator

    hi.
    i want to use a lov where i want to pass a variable using like operator.
    my query is
    select empno,name from table where empno like ':ed%';
    my empno is A001 TO A199 AND B001 TO B199 so i want show either A% or B% empno
    how can i do this ?
    reagrds

    kindly press Shift+F1 at a time you face this error to see the exact Oracle error message.
    and provide us with that detail
    and its better if you start new topic for that error... because that will be new error,,,
    -- Aamir Arif
    Edited by: Aamiz on Apr 7, 2010 12:27 PM

  • 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.

  • 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

  • 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

  • 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

  • Issue with query using minus operation

    Hello All,
    I have data set of all organization numbers like as below
    Dataset:
    ('528801','528802','536101','536102','100601','536401','536402','530701','536501','536502','540501','599101','133301',
    '531101','143101','536601','536602','534401','535501','535401','536801','536802','531001','537501','537502','540601','540801','528401')
    And i also have a table W_INT_ORG_D where in it has column like ORG_NUM which holds the organization numbers in the database, now i am trying to find out the exclusive organization numbers in the data set that does not exist in W_INT_ORG_D using some oracle sql query.
    Below is the sql i wrote though my query is wrong probably you could able to understand what i am trying to say or achieve, i am not ok with creating another table and filling in the data and later compare both tables, i want to do that without creating any extra table. Please let me know if you have any idea to do this, appreciate your time.
    Query:_
    WITH ABC AS
    ('528801','528802','536101','536102','100601','536401','536402','530701','536501','536502','540501','599101','133301',
    '531101','143101','536601','536602','534401','535501','535401','536801','536802','531001','537501','537502','540601','540801','528401')
    SELECT DISTINCT ORG_NUM
    FROM W_INT_ORG_D, ABC
    WHERE DATASOURCE_NUM_ID='211'
    AND ORG_NUM IN
    ('528801','528802','536101','536102','100601','536401','536402','530701','536501','536502','540501','599101','133301',
    '531101','143101','536601','536602','534401','535501','535401','536801','536802','531001','537501','537502','540601','540801','528401')
    MINUS
    SELECT * FROM ABC
    Thanks,
    Sam

    This wil give a list of organization numbers in dataset that are not present in the view:
    SELECT column_value org_num
       FROM TABLE(sys.odciVarchar2List(
                                       '528801',
                                       '528802',
                                       '536101',
                                       '536102',
                                       '100601',
                                       '536401',
                                       '536402',
                                       '530701',
                                       '536501',
                                       '536502',
                                       '540501',
                                       '599101',
                                       '133301',
                                       '531101',
                                       '143101',
                                       '536601',
                                       '536602',
                                       '534401',
                                       '535501',
                                       '535401',
                                       '536801',
                                       '536802',
                                       '531001',
                                       '537501',
                                       '537502',
                                       '540601',
                                       '540801',
                                       '528401'
    MINUS
    SELECT  DISTINCT ORG_NUM
       FROM  W_INT_ORG_D
       WHERE DATASOURCE_NUM_ID='211'
    /SY.
    Edited by: Solomon Yakobson on Jun 29, 2009 10:49 AM

  • 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

  • Prioritizing a set by using union operator

    My requirement is to print data whose log_in_id starts with a and end with y first, then to print data starting with a and b.
    select * from userid where log_in_id like 'a%y' union select * from userid where log_in_id like 'a%' or log_in_id like 'b%'

    Why go through the table twice? I would do something like:
    SQL> SELECT log_in_id
      2  FROM (SELECT 'bob' log_in_id FROM dual
      3        UNION ALL
      4        SELECT 'bill' from dual
      5        UNION ALL
      6        SELECT 'ally' from dual
      7        UNION ALL
      8        SELECT 'abby' from dual
      9        UNION ALL
    10        SELECT 'allen' from dual
    11        UNION ALL
    12        SELECT 'albert' from dual)
    13  ORDER BY CASE WHEN log_in_id LIKE 'a%y' THEN 1 ELSE 2 END,
    14           log_in_id;
    LOG_IN
    abby
    ally
    albert
    allen
    bill
    bobHTH
    John

Maybe you are looking for

  • I have 4 kids, do I need a separate icloud and a separate itunes account for each?

    What's the best way to manage multiple devices,for separate individuals, within one itunes account? I have 4 kids who don't want to read each one's texts but want to share music & apps and still have their own individual itunes accounts.

  • Changing the column position & width using Screen Variant..

    Hi Experts,     Iam trying to change the column position and width for the standard transaction (eg. FB60 or VA02) using the transaction code SHD0 (Transaction and Screen Variant).     Iam able to create and save the transaction and screen variant an

  • How to avoid database logon dialog on every action of refreshing reports

    I am using Crystal reports 208 SP2 and has a database connection to oracle database. Connection is esablished and report retrieves desired data, The problem is when ever i open this report ( which has this connection set) and do a refresh,  the repor

  • Before Update Trigger has mutating problem

    I'm getting a mutating problem with this updating trigger. I'm not sure how to deal with it. Here is my code: CREATE OR REPLACE TRIGGER WTL_SMP_TRG2 BEFORE UPDATE ON WTL_SAMPLES FOR EACH ROW DECLARE      sampleCount NUMBER(1) := 0;      dupLabSampleI

  • Unchecked Keywords in Bridge

    I'm trying to keyword multiple images by selecting them all and then checking off the box next to each keyword. The problem is that for some images, the checkmark disappears. It seems like the keyword is still in the metadata after it is unchecked, b