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

Similar Messages

  • Using union all and rownum

    Hello again.
    Another question.
    Can I query with union all and stop it when I get N rows.
    For example:
    select 1 from dba_segments
    union all
    select 2 from dba_segments where
    union all
    select 3 from dba_segments where;
    and get the 100 first rows without doing the whole query:(not like that-->)
    select * from (
    select 1 from dba_segments
    union all
    select 2 from dba_segments where
    union all
    select 3 from dba_segments where)
    where rownum < 100);
    I want the query will stop when there are 100 rows in the result set.
    thank you!

    You already posted your own answer. It just seems you don't want to use it.
    ROWNUM is NOT assigned until the rows are selected to be returned. So you need to wrap the three inner queries into a query that uses ROWNUM.

  • 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

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

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

  • Performance using UNION ALL

    Hello
    i have 2 schemas S1 and S2 containing complex relational tables. The tables in each schema are related to each other via foreign key relationships. i made views for feature tables in both the schemas , querying column values from their related tables.
    the data structure in both the schemas are exactly the same. Dut to management reasons we have to split them in 2 schemas. S1 contain data for region A and S2 contains data from region B. Now the client wants to see a combined data from region A & B.
    we are planning to create another schema S3 and make views combining views from S1 and S2 in both schemas (V1 in S1 + V1 in S2) using UNION ALL.
    Does UNION ALL will make use of the indexes we already built for parent tables in S1 and S2? Will there be a performance degradation using this approach? What can be the best approach? Our client needs to see real time data....
    regards
    sam

    Since union does an extra sort it has a performance difference compared to union all.
    SQL> select user from dual union select user from dual ;
    USER
    HR
    SQL> select user from dual union all select user from dual ;
    USER
    HR
    HRİf there is up to date and appropriate object statistics Oracle's Cost Based Optimizer will choose best access path, join method and join order depending on your query. Only exceptions are hints, outlines and sql profiles since they stabilize the execution plan.
    For further commenting please post your oracle version, query's test results and its statistics taken from sql*plus timing and autotrace options - http://www.bhatipoglu.com/entry/17/oracle-performance-analysis-tracing-and-performance-evaluation

  • UNION ALL and UNION performance issue

    Hi All,
    I am trying to figure out the data for which only receive transaction has been done and further processing is pending. These transactions include all PO, RMA , ISO etc...
    I have to use UNION ALL in this case as for RMA and ISO, details which i want are not able to gather in a single query.
    But query is taking a lot of time ...may be around 30..mins in UNION ALL while 6 to 7 mins in UNION.
    To get all records I must have to use UNION ALL...
    So kindly suggest the solution for this problem
    Thanks
    Sachin
    Query is given below...
    SELECT /* + FIRST_ROWS */ DECODE(rsl.SOURCE_DOCUMENT_CODE,'REQ',(SELECT org1.ORGANIZATION_NAME
                                                           FROM     org_organization_definitions org1
                                                           WHERE org1.ORGANIZATION_ID =
                                                           rsl.FROM_ORGANIZATION_ID)) Vendor_Name
    ,rsh.RECEIPT_NUM Receipt_Number
         ,TO_CHAR(rt3.TRANSACTION_DATE,'Mon-DD-YYYY HH:MM:SS') Receipt_Date_and_Time
         ,msi.SEGMENT1 Part_Number
         ,msi.DESCRIPTION Part_Name
         ,rt3.QUANTITY Quantity
         ,rt3.UNIT_OF_MEASURE UOM
         ,NULL ASL_Status
         --for ISO no asl flag ASL Flag
         ,TO_CHAR(TRUNC((((86400*(SYSDATE-rt3.TRANSACTION_DATE))/60)/60)/24))|| ' Days ' || TO_CHAR(TRUNC(((86400*(SYSDATE-rt3.TRANSACTION_DATE))/60)/60)-24*(TRUNC((((86400*(SYSDATE-rt3.TRANSACTION_DATE))/60)/60)/24)))|| ' Hours' Days_and_hours_passed
         ,DECODE(
                        NVL(msi.max_minmax_quantity,0) ,
                        0 , 0 ,
                        (NVL(msi.max_minmax_quantity,0) -
                        NVL(inmohqd.onhand,0))
                             * 100
                             / NVL(msi.max_minmax_quantity,0)
                        ) gap_percent
    FROM rcv_transactions rt3
         ,rcv_shipment_headers rsh
         ,rcv_shipment_lines rsl
         ,mtl_system_items msi
         ,org_organization_definitions org
         --,MTL_ONHAND_QUANTITIES_DETAIL moqhd
         ,(SELECT NVL(SUM(primary_transaction_quantity),0) onhand,INVENTORY_ITEM_ID item_id,ORGANIZATION_ID organization_id
         FROM      mtl_onhand_quantities_detail
         WHERE SUBINVENTORY_CODE NOT IN ('Wip_SF','Wip_Int','Reject','Scrap','FG Trading','FG')
         GROUP BY INVENTORY_ITEM_ID, ORGANIZATION_ID) inmohqd
    WHERE inmohqd.item_id(+) = msi.INVENTORY_ITEM_ID
         AND inmohqd.organization_id(+) = msi.ORGANIZATION_ID
         --AND inmoqhd.SUBINVENTORY_CODE NOT IN  ('Wip_SF','Wip_Int','Reject','Scrap','FG Trading','FG')
         AND msi.INVENTORY_ITEM_ID = rsl.ITEM_ID
         AND rsh.SHIPMENT_HEADER_ID = rsl.SHIPMENT_HEADER_ID
         AND org.ORGANIZATION_ID = rt3.ORGANIZATION_ID
         AND msi.ORGANIZATION_ID = rt3.ORGANIZATION_ID
         AND rsh.SHIPMENT_HEADER_ID = rt3.SHIPMENT_HEADER_ID
         AND rsl.SHIPMENT_HEADER_ID = rt3.SHIPMENT_HEADER_ID
         AND rsl.SHIPMENT_LINE_ID = rt3.SHIPMENT_LINE_ID
         AND rt3.PO_HEADER_ID IS NULL
         AND TRUNC(rt3.TRANSACTION_DATE) <= TRUNC(p_tilldate)
         AND rsl.TO_ORGANIZATION_ID = p_organization_id
         AND rsh.ORGANIZATION_ID = p_organization_id
         AND CONCAT(TRIM(rt3.SHIPMENT_HEADER_ID),TRIM(rt3.SHIPMENT_LINE_ID)) IN
         SELECT CONCAT(TRIM(rt1.SHIPMENT_HEADER_ID),TRIM(rt1.SHIPMENT_LINE_ID))
         FROM     rcv_transactions rt1
         WHERE NOT EXISTS(
         SELECT 1
              FROM     rcv_transactions rt2
              WHERE     rt2.TRANSACTION_TYPE <> 'RECEIVE'
                        AND rt1.SHIPMENT_HEADER_ID = rt2.SHIPMENT_HEADER_ID
                        AND rt1.SHIPMENT_LINE_ID = rt2.SHIPMENT_LINE_ID
                        AND rt2.ORGANIZATION_ID = p_organization_id
    UNION
    SELECT /* + FIRST_ROWS */ pv.VENDOR_NAME Vendor_Name
         ,rsh.RECEIPT_NUM Receipt_Number
         ,TO_CHAR(rt.TRANSACTION_DATE,'Mon-DD-YYYY HH:MM:SS') Receipt_Date_and_Time
         ,msi.SEGMENT1 Part_Number
         ,msi.DESCRIPTION Part_Name
         ,rt.QUANTITY Quantity
         ,rt.UNIT_OF_MEASURE UOM
         --start 001
         ,NVL((SELECT DISTINCT DECODE (ASL_STATUS_ID,1,'New',2,'Approved','To be checked')
                   FROM po_approved_supplier_list pasl
                   WHERE pasl.item_id=rsl.ITEM_ID
                             AND pasl.VENDOR_ID(+) = pv.VENDOR_ID
                             AND pasl.VENDOR_SITE_ID(+) = pvs.VENDOR_SITE_ID),'No_data') ASL_Status
              --end 001
              ,TO_CHAR(TRUNC((((86400*(SYSDATE-rt.TRANSACTION_DATE))/60)/60)/24))|| ' Days ' || TO_CHAR(TRUNC(((86400*(SYSDATE-rt.TRANSACTION_DATE))/60)/60)-24*(TRUNC((((86400*(SYSDATE-rt.TRANSACTION_DATE))/60)/60)/24)))|| ' Hours' Days_and_hours_passed          ,DECODE(
                   NVL(msi.max_minmax_quantity,0) ,
              0 , 0 ,
              (NVL(msi.max_minmax_quantity,0) -
              NVL(inmohqd.onhand,0))
                   * 100
                   / NVL(msi.max_minmax_quantity,0)
              ) gap_percent
    FROM rcv_transactions rt
         ,po_vendors pv
         ,po_vendor_sites_all pvs
         ,rcv_shipment_headers rsh
         ,rcv_shipment_lines rsl
         ,mtl_system_items msi
         ,org_organization_definitions org
         --,mtl_onhand_quantities_detail moqhd
         ,(SELECT NVL(SUM(primary_transaction_quantity),0) onhand,INVENTORY_ITEM_ID item_id,ORGANIZATION_ID organization_id
         FROM      mtl_onhand_quantities_detail
         WHERE SUBINVENTORY_CODE NOT IN ('Wip_SF','Wip_Int','Reject','Scrap','FG Trading','FG')
         GROUP BY INVENTORY_ITEM_ID, ORGANIZATION_ID) inmohqd
    WHERE inmohqd.item_id(+) = msi.INVENTORY_ITEM_ID
         AND inmohqd.ORGANIZATION_ID(+) = msi.ORGANIZATION_ID
         --AND inmoqhd.SUBINVENTORY_CODE NOT IN  ('Wip_SF','Wip_Int','Reject','Scrap','FG Trading','FG')
         AND msi.INVENTORY_ITEM_ID = rsl.ITEM_ID
         AND rsh.SHIPMENT_HEADER_ID = rsl.SHIPMENT_HEADER_ID
         AND pv.VENDOR_ID = pvs.VENDOR_ID
         AND org.ORGANIZATION_ID = rt.ORGANIZATION_ID
         AND msi.ORGANIZATION_ID = rt.ORGANIZATION_ID
         AND pvs.VENDOR_SITE_ID = rt.VENDOR_SITE_ID
         AND pv.VENDOR_ID = rt.VENDOR_ID
         AND rsh.SHIPMENT_HEADER_ID = rt.SHIPMENT_HEADER_ID
         AND rsl.SHIPMENT_HEADER_ID = rt.SHIPMENT_HEADER_ID
         AND rsl.SHIPMENT_LINE_ID = rt.SHIPMENT_LINE_ID
         AND TRUNC(rt.TRANSACTION_DATE) <= TRUNC(p_tilldate)
         AND rsl.TO_ORGANIZATION_ID = p_organization_id
         AND CONCAT(TRIM(rt.SHIPMENT_HEADER_ID),TRIM(rt.SHIPMENT_LINE_ID)) IN
              SELECT CONCAT(TRIM(rt1.SHIPMENT_HEADER_ID),TRIM(rt1.SHIPMENT_LINE_ID))
              FROM RCV_TRANSACTIONS rt1
              WHERE rt1.TRANSACTION_TYPE = 'RECEIVE'
                   AND rt1.DESTINATION_TYPE_CODE = 'RECEIVING'
                   AND rt1.PO_HEADER_ID IS NOT NULL
                   AND NOT EXISTS(
                   SELECT 1
                        FROM     RCV_TRANSACTIONS rt2
                        WHERE     rt2.SHIPMENT_HEADER_ID = rt1.SHIPMENT_HEADER_ID
                                  AND rt2.SHIPMENT_LINE_ID = rt1.SHIPMENT_LINE_ID
                                  AND rt2.TRANSACTION_TYPE <> 'RECEIVE'
         )

    In this case, for selected columns, all data is same for one of the RMA with more than one line. So UNION will skip one of the records. However, shipment line id are different for both records, so by selecting it in select list is solving the problem and so no need to use UNION ALL. But, anyhow UNION ALL is better than UNION in performance as it does not require to sort. Then why I am facing this problem...
    Kindly suggest
    Regards,
    Sachin

  • Drill down problem when using union all combination

    Hi All,
    I have a simple report with a drill down. The report has three columns Region, Sales, Flag... which will drill down to detail level of sales. The Flag column has Y, N values and we added 'All' Value in flag so that the user can select Y, N and All from the table prompt in the report . We have used union all in the report using combination to add the ' All ' Value in the flag. The problem is that now the main report is not passing the Flag values to the detail report. Flag is prompted in the filter in detail report.
    If I remove the 'All' value from Analysis with only Y N selection criteria the drill down works.
    Is there any work around? I have to use table prompt and All value selection in flag for drill down.
    Thanks,
    Virat

    The problem is without union all when doing combination of analysis drill down works, when I use combination drill down does not work because it does not pass the parameters for flag . I have used union all to add All value in flag.

  • PS CS6: Images sometimes not saved when using Close All and instructed to save

    I thought I had made a crazy mistake when this happened earlier today, but it just did it again and I was paying close attention. 
    I often open multiple images to make several changes, then use Close All and when it prompts "Do you want to save changes to ... before closing?" I check off the box to "Apply to all" and say Yes.   This saves lots of time when adjusting several multi-hundred MB images.  Imagine my surprise today when it closed an image without saving!  I had to repeat about 30 minutes of work as a result. 
    I thought I had somehow accidentally clicked "No" to saving, so I made sure to pay close attention the next few times I used Close All to save work.  It worked fine until a moment ago when it did it again.
    Has anyone seen something like this?  I can't find anything in searching.  In all my time using this feature in PS I never once had a problem before.

    Thanks for the reply.
    I just upgraded to CS6 from CS5 a few days ago, and this is my first week in heavy usage. 
    I do have Save in Background turned on.  I am saving locally.  I also have auto recovery saves turned on, at 5 minute intervals (CS6 has crashed a few times on me)
    Yesterday I used Close All with Save maybe 10 times, and it exhibited this behavior 2 of those times. 
    In the two cases, I had 3 PSDs open, each a little over 400 mb in size.  It seemed to save two of the images, but left one unsaved.  I noticed that instead of spending several seconds saving, it would quickly just close that image - as though it believed no changes had been made.  The changes that had been made to the image were routine - add some adjustment layers, some masks etc.
    I have tried to reproduce it by opening the same images, making similar changes and then repeating Close All with Save, but so far no (bad) luck.  Idle speculation - could it have something to do with the frequent interval of autorecovery saves that I do? Some kind of conflict?  Or is it something to do with background saves?  Definitely never saw this in previous versions of PS.
    As a workaround, I have made a simple action that saves an image and apply it in batch.  I just can't risk losing work.

  • Inconsistent SQL results when using View with UNION-ALL and table function

    Can any of you please execute the below scripts and check the output. In the table type variable, I am adding 4 distinct object ids, where as in the result, I get only the row pertaining to last id in the table type variable. Same row is returned 4 times (4= number of values in the table type).
    This scenario is occurring in our product with a SQL with exactly same pattern. I could simulate the same issue with the sample script I have provided.
    Database version: 11.2.0.3 Enterprise Edition, Single node
    Thank you.
    CREATE TABLE TEMP_T1 AS SELECT * FROM ALL_OBJECTS;
    CREATE TABLE TEMP_T2 AS SELECT * FROM ALL_OBJECTS;
    UPDATE TEMP_T2 SET OBJECT_ID = OBJECT_ID * 37;
    CREATE UNIQUE INDEX TEMP_T1_U1 ON TEMP_T1(OBJECT_ID);
    CREATE UNIQUE INDEX TEMP_T2_U1 ON TEMP_T2(OBJECT_ID);
    CREATE OR REPLACE VIEW TEMP_T1T2_V AS
    SELECT * FROM TEMP_T1 UNION ALL SELECT * FROM TEMP_T2;
    CREATE OR REPLACE TYPE TEMP_OBJ_TYPE AS OBJECT (OBJ_ID NUMBER);
    CREATE OR REPLACE TYPE TEMP_OBJ_TAB_TYPE IS TABLE OF TEMP_OBJ_TYPE;
    SET SERVEROUTPUT ON;
    DECLARE
    TYPE TEMP_T1T2_V_ROW_TAB_TYPE IS TABLE OF TEMP_T1T2_V%ROWTYPE;
    TEMP_T1T2_V_ROW_TAB TEMP_T1T2_V_ROW_TAB_TYPE;
    TEMP_OBJ_TAB TEMP_OBJ_TAB_TYPE := TEMP_OBJ_TAB_TYPE();
    PROCEDURE ADD_TO_TEMP_OBJ_TAB(OBJ_ID IN NUMBER) IS
    BEGIN
    TEMP_OBJ_TAB.EXTEND;
    TEMP_OBJ_TAB(TEMP_OBJ_TAB.LAST) := TEMP_OBJ_TYPE(OBJ_ID);
    END;
    BEGIN
    ADD_TO_TEMP_OBJ_TAB(100);
    ADD_TO_TEMP_OBJ_TAB(116);
    ADD_TO_TEMP_OBJ_TAB(279);
    ADD_TO_TEMP_OBJ_TAB(364);
    DBMS_OUTPUT.PUT_LINE('=====================');
    FOR I IN TEMP_OBJ_TAB.FIRST..TEMP_OBJ_TAB.LAST
    LOOP
    DBMS_OUTPUT.PUT_LINE('OBJ_ID = '||TEMP_OBJ_TAB(I).OBJ_ID);
    END LOOP;
    DBMS_OUTPUT.PUT_LINE('---------------------');
    SELECT * BULK COLLECT INTO TEMP_T1T2_V_ROW_TAB
    FROM TEMP_T1T2_V VW
    WHERE ((VW.OBJECT_ID) IN (SELECT OBJ_ID
    FROM TABLE(CAST(TEMP_OBJ_TAB AS TEMP_OBJ_TAB_TYPE))));
    FOR I IN TEMP_OBJ_TAB.FIRST..TEMP_OBJ_TAB.LAST
    LOOP
    DBMS_OUTPUT.PUT_LINE('OBJ_ID = '||TEMP_OBJ_TAB(I).OBJ_ID);
    END LOOP;
    DBMS_OUTPUT.PUT_LINE('---------------------');
    IF TEMP_T1T2_V_ROW_TAB.COUNT > 0 THEN
    FOR I IN TEMP_T1T2_V_ROW_TAB.FIRST..TEMP_T1T2_V_ROW_TAB.LAST
    LOOP
    DBMS_OUTPUT.PUT_LINE(TEMP_T1T2_V_ROW_TAB(I).OBJECT_ID||' : '||TEMP_T1T2_V_ROW_TAB(I).OBJECT_NAME);
    END LOOP;
    ELSE
    DBMS_OUTPUT.PUT_LINE('NO ROWS RETURNED!');
    END IF;
    DBMS_OUTPUT.PUT_LINE('---------------------');
    END;
    /

    I can reproduce it:
    SQL*Plus: Release 11.2.0.3.0 Production on Tue Oct 30 14:05:39 2012
    Copyright (c) 1982, 2011, Oracle.  All rights reserved.
    Enter user-name: scott
    Enter password:
    Connected to:
    Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
    With the Partitioning, OLAP, Data Mining and Real Application Testing options
    SQL> select  *
      2    from  v$version
      3  /
    BANNER
    Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
    PL/SQL Release 11.2.0.3.0 - Production
    CORE    11.2.0.3.0      Production
    TNS for 64-bit Windows: Version 11.2.0.3.0 - Production
    NLSRTL Version 11.2.0.3.0 - Production
    SQL> CREATE TABLE TEMP_T1 AS SELECT * FROM ALL_OBJECTS;
    Table created.
    SQL>
    SQL> CREATE TABLE TEMP_T2 AS SELECT * FROM ALL_OBJECTS;
    Table created.
    SQL>
    SQL> UPDATE TEMP_T2 SET OBJECT_ID = OBJECT_ID * 37;
    72883 rows updated.
    SQL>
    SQL> CREATE UNIQUE INDEX TEMP_T1_U1 ON TEMP_T1(OBJECT_ID);
    Index created.
    SQL>
    SQL> CREATE UNIQUE INDEX TEMP_T2_U1 ON TEMP_T2(OBJECT_ID);
    Index created.
    SQL>
    SQL> CREATE OR REPLACE VIEW TEMP_T1T2_V AS
      2  SELECT * FROM TEMP_T1 UNION ALL SELECT * FROM TEMP_T2;
    View created.
    SQL>
    SQL> CREATE OR REPLACE TYPE TEMP_OBJ_TYPE AS OBJECT (OBJ_ID NUMBER)
      2  /
    Type created.
    SQL> CREATE OR REPLACE TYPE TEMP_OBJ_TAB_TYPE IS TABLE OF TEMP_OBJ_TYPE
      2  /
    Type created.
    SQL> SET SERVEROUTPUT ON;
    SQL>
    SQL> DECLARE
      2  TYPE TEMP_T1T2_V_ROW_TAB_TYPE IS TABLE OF TEMP_T1T2_V%ROWTYPE;
      3  TEMP_T1T2_V_ROW_TAB TEMP_T1T2_V_ROW_TAB_TYPE;
      4  TEMP_OBJ_TAB TEMP_OBJ_TAB_TYPE := TEMP_OBJ_TAB_TYPE();
      5  PROCEDURE ADD_TO_TEMP_OBJ_TAB(OBJ_ID IN NUMBER) IS
      6  BEGIN
      7  TEMP_OBJ_TAB.EXTEND;
      8  TEMP_OBJ_TAB(TEMP_OBJ_TAB.LAST) := TEMP_OBJ_TYPE(OBJ_ID);
      9  END;
    10  BEGIN
    11  ADD_TO_TEMP_OBJ_TAB(100);
    12  ADD_TO_TEMP_OBJ_TAB(116);
    13  ADD_TO_TEMP_OBJ_TAB(279);
    14  ADD_TO_TEMP_OBJ_TAB(364);
    15  DBMS_OUTPUT.PUT_LINE('=====================');
    16  FOR I IN TEMP_OBJ_TAB.FIRST..TEMP_OBJ_TAB.LAST
    17  LOOP
    18  DBMS_OUTPUT.PUT_LINE('OBJ_ID = '||TEMP_OBJ_TAB(I).OBJ_ID);
    19  END LOOP;
    20  DBMS_OUTPUT.PUT_LINE('---------------------');
    21  SELECT * BULK COLLECT INTO TEMP_T1T2_V_ROW_TAB
    22  FROM TEMP_T1T2_V VW
    23  WHERE ((VW.OBJECT_ID) IN (SELECT OBJ_ID
    24  FROM TABLE(CAST(TEMP_OBJ_TAB AS TEMP_OBJ_TAB_TYPE))));
    25  FOR I IN TEMP_OBJ_TAB.FIRST..TEMP_OBJ_TAB.LAST
    26  LOOP
    27  DBMS_OUTPUT.PUT_LINE('OBJ_ID = '||TEMP_OBJ_TAB(I).OBJ_ID);
    28  END LOOP;
    29  DBMS_OUTPUT.PUT_LINE('---------------------');
    30  IF TEMP_T1T2_V_ROW_TAB.COUNT > 0 THEN
    31  FOR I IN TEMP_T1T2_V_ROW_TAB.FIRST..TEMP_T1T2_V_ROW_TAB.LAST
    32  LOOP
    33  DBMS_OUTPUT.PUT_LINE(TEMP_T1T2_V_ROW_TAB(I).OBJECT_ID||' : '||TEMP_T1T2_V_ROW_TAB(I).OBJECT_NAME);
    34  END LOOP;
    35  ELSE
    36  DBMS_OUTPUT.PUT_LINE('NO ROWS RETURNED!');
    37  END IF;
    38  DBMS_OUTPUT.PUT_LINE('---------------------');
    39  END;
    40  /
    =====================
    OBJ_ID = 100
    OBJ_ID = 116
    OBJ_ID = 279
    OBJ_ID = 364
    OBJ_ID = 100
    OBJ_ID = 116
    OBJ_ID = 279
    OBJ_ID = 364
    364 : I_AUDIT
    364 : I_AUDIT
    364 : I_AUDIT
    364 : I_AUDIT
    PL/SQL procedure successfully completed.
    SQL> column object_name format a30
    SQL> select  object_id,
      2          object_name
      3    from  dba_objects
      4    where object_id in (100,116,279,364)
      5  /
    OBJECT_ID OBJECT_NAME
           100 ORA$BASE
           116 DUAL
           279 MAP_OBJECT
           364 I_AUDIT
    SQL>  Works fine in:
    =====================
    OBJ_ID = 100
    OBJ_ID = 116
    OBJ_ID = 279
    OBJ_ID = 364
    OBJ_ID = 100
    OBJ_ID = 116
    OBJ_ID = 279
    OBJ_ID = 364
    100 : ORA$BASE
    116 : DUAL
    364 : SYSTEM_PRIVILEGE_MAP
    279 : MAP_OBJECT
    PL/SQL procedure successfully completed.
    SQL> select  object_id,
      2          object_name
      3    from  dba_objects
      4    where object_id in (100,116,279,364)
      5  /
    OBJECT_ID OBJECT_NAME
          100 ORA$BASE
          116 DUAL
          364 SYSTEM_PRIVILEGE_MAP
          279 MAP_OBJECT
    SQL> select  *
      2    from  v$version
      3  /
    BANNER
    Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
    PL/SQL Release 11.2.0.1.0 - Production
    CORE    11.2.0.1.0      Production
    TNS for 32-bit Windows: Version 11.2.0.1.0 - Production
    NLSRTL Version 11.2.0.1.0 - Production
    SQL>SY.
    Edited by: Solomon Yakobson on Oct 30, 2012 2:14 PM

  • Text query using a Multi Column datastore index slow

    I have created a text index using multi column datastore preference. I have specified two clob columns in my preference. Searching on this new index works, but it is slower than I expected.
    I have done the following comparison:
    My original two clob columns are: DocumentBody and DocumentFields. I have built an individual text index on each column. My new column with Multi Column index is DocumentBodyAndFields;
    I did two queries:
    1. search 'dog' on DocumentBody UNION search 'dog' on DocumentFields;
    2. search 'dog' on DocumentBodyAndFields;
    I would think the second search should be faster than the first one because it is a single query. But this is not the case. The second query is consistently slower than the first query by about 10-20%.
    Things are getting much worse when I search on preceding wildcards. If I search '%job', the multi column index is twice as slow as the first query! I am very confused by this result. Is this a bug?

    I am unable to reproduce the performance problem. In my tests, the search that uses the multicolumn_datastore performs better, as demonstrated below. Can you provide a similar test case that shows the table structure, datastore, index creations, and explain plan?
    SCOTT@orcl_11g> CREATE TABLE your_tab
      2    (DocumentId            NUMBER,
      3       DocumentBody            CLOB,
      4       DocumentFields            CLOB,
      5       DocumentBodyAndFields  VARCHAR2 (1))
      6  /
    Table created.
    SCOTT@orcl_11g> INSERT ALL
      2  INTO your_tab VALUES (-1, 'adog', 'bdog', NULL)
      3  INTO your_tab VALUES (-2, 'adog', 'whatever', NULL)
      4  INTO your_tab VALUES (-3, 'whatever', 'bdog', NULL)
      5  SELECT * FROM DUAL
      6  /
    3 rows created.
    SCOTT@orcl_11g> INSERT INTO your_tab
      2  SELECT object_id, object_name, object_name, NULL
      3  FROM   all_objects
      4  /
    69063 rows created.
    SCOTT@orcl_11g> BEGIN
      2    CTX_DDL.CREATE_PREFERENCE
      3        ('your_datastore', 'MULTI_COLUMN_DATASTORE');
      4    CTX_DDL.SET_ATTRIBUTE
      5        ('your_datastore', 'COLUMNS', 'DocumentBody, DocumentFields');
      6  END;
      7  /
    PL/SQL procedure successfully completed.
    SCOTT@orcl_11g> CREATE INDEX your_idx1 ON your_tab (DocumentBody)
      2  INDEXTYPE IS CTXSYS.CONTEXT
      3  /
    Index created.
    SCOTT@orcl_11g> CREATE INDEX your_idx2 ON your_tab (DocumentFields)
      2  INDEXTYPE IS CTXSYS.CONTEXT
      3  /
    Index created.
    SCOTT@orcl_11g> CREATE INDEX your_idx3 ON your_tab (DocumentBodyAndFields)
      2  INDEXTYPE IS CTXSYS.CONTEXT
      3  PARAMETERS ('DATASTORE your_datastore')
      4  /
    Index created.
    SCOTT@orcl_11g> EXEC DBMS_STATS.GATHER_TABLE_STATS (USER, 'YOUR_TAB')
    PL/SQL procedure successfully completed.
    SCOTT@orcl_11g> SET TIMING ON
    SCOTT@orcl_11g> SET AUTOTRACE ON EXPLAIN
    SCOTT@orcl_11g> SELECT DocumentId FROM your_tab
      2  WHERE  CONTAINS (DocumentBody, '%dog') > 0
      3  UNION
      4  SELECT DocumentId FROM your_tab
      5  WHERE  CONTAINS (DocumentFields, '%dog') > 0
      6  /
    DOCUMENTID
            -3
            -2
            -1
    Elapsed: 00:00:00.65
    Execution Plan
    Plan hash value: 4118340734
    | Id  | Operation                     | Name      | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT              |           |     4 |   576 |     2 (100)| 00:00:01 |
    |   1 |  SORT UNIQUE                  |           |     4 |   576 |     2 (100)| 00:00:01 |
    |   2 |   UNION-ALL                   |           |       |       |            |          |
    |   3 |    TABLE ACCESS BY INDEX ROWID| YOUR_TAB  |     2 |   288 |     0   (0)| 00:00:01 |
    |*  4 |     DOMAIN INDEX              | YOUR_IDX1 |       |       |     0   (0)| 00:00:01 |
    |   5 |    TABLE ACCESS BY INDEX ROWID| YOUR_TAB  |     2 |   288 |     0   (0)| 00:00:01 |
    |*  6 |     DOMAIN INDEX              | YOUR_IDX2 |       |       |     0   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       4 - access("CTXSYS"."CONTAINS"("DOCUMENTBODY",'%dog')>0)
       6 - access("CTXSYS"."CONTAINS"("DOCUMENTFIELDS",'%dog')>0)
    SCOTT@orcl_11g> SELECT DocumentId FROM your_tab
      2  WHERE  CONTAINS (DocumentBodyAndFields, '%dog') > 0
      3  /
    DOCUMENTID
            -1
            -2
            -3
    Elapsed: 00:00:00.28
    Execution Plan
    Plan hash value: 65113709
    | Id  | Operation                   | Name      | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT            |           |     4 |    76 |     0   (0)| 00:00:01 |
    |   1 |  TABLE ACCESS BY INDEX ROWID| YOUR_TAB  |     4 |    76 |     0   (0)| 00:00:01 |
    |*  2 |   DOMAIN INDEX              | YOUR_IDX3 |       |       |     0   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       2 - access("CTXSYS"."CONTAINS"("DOCUMENTBODYANDFIELDS",'%dog')>0)
    SCOTT@orcl_11g>

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

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

  • Materalized view with union all and fast referesh

    I have a one view which is very slow. in this view we are joining many tables and many union all queries.
    now I am planing to make materalized view
    Tell me how i will created view with fast refresh with union all query.
    Pls help its urgent..
    Thanks
    Reena

    Refer to the Replication Manual for the create syntax and exceptions.

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

Maybe you are looking for

  • XRANDR HDMI problem NVIDIA Optimus proprietary

    Hi, Can someone help me understand why when I switch the audio to HIMI the frequency is accelerated? I followed the wiki about the sampling frequency of pulseaudio but has no effect. in practice, the audio is slightly accelerated it seems one octave

  • Can a Mini DisplayPort to Dual-Link DVI Adapter do the same job as the Mini DisplayPort to DVI Adapter?

    Can a Mini DisplayPort to Dual-Link DVI Adapter do the same job as the Mini DisplayPort to DVI Adapter?  Meaning, can I connect a DVI screen less than 30 inches?  Why would I buy the expensive product?  Simply because I might have to sometimes work w

  • Foreign trade data - Embargo for military materials for certain countries

    We make a product that can be used in the military. We do not ship anything to UN Embargo countries, we cannot ship certain materials that are military related to a list of about 20 countries, then all other countries for these military materials req

  • Panels in a row in a scroll pane.

    Hi, in my application, i have a UI frame, which contains a scroll pane that has a panel, which contains a few hundreds of panels, lined up vertically. Each of these panels contais an icon, a label, a text field and a few more label fields and more te

  • Full Disk!

    hello, ive been having this problem for like the last couple months. i keep getting notifications that my startup disk is full or my hard disk is full. these notifications come up sooo many times and sometimes one right after the other. ive read thro