Alternative/enhancement to union query?

Hello,
I have 2 sets of similar data which I am joining together with a union query.
Simplified E.g.
*Table A*
Name Dept
Ben    1
Amy   3
Ken    3
*Table B*
Name Dept
Jim    1
John  2
Sue   3
select Name, Dept
from table A
UNION
select Name, Dept
from table BWhat I would like to do is ONLY include data from the second part of the union query where it joins with some data from the first part of the union query.
E.g.
select Name, Dept
from table A
UNION
select Name, Dept
from table B
where Dept in (select distinct Dept from A)Therefore John that works in Dept 2 would not be included in the results.
Is there a better or more efficient way of doing this than my example using the subquery as part of the where clause?
Many thanks,
Hazel

Hi, Hazel,
What you posted is as good as you can get without changing the tables.
You don't have to say DISTINCT in the IN-subquery:
where   Dept in (  select  Dept
                   from    A
                )will get the same results, perhaps a little faster.

Similar Messages

  • Alternative/enhancement to union query? Duplicate - please delete

    Hello,
    I have 2 sets of similar data which I am joining together with a union query.
    Simplified E.g.
    *Table A*
    Name Dept
    Ben    1
    Amy   3
    Ken    3
    *Table B*
    Name Dept
    Jim    1
    John  2
    Sue   3
    select Name, Dept
    from table A
    UNION
    select Name, Dept
    from table BWhat I would like to do is ONLY include data from the second part of the union query where it joins with some data from the first part of the union query.
    E.g.
    select Name, Dept
    from table A
    UNION
    select Name, Dept
    from table B
    where Dept in (select distinct Dept from A)Therefore John that works in Dept 2 would not be included in the results.
    Is there a better or more efficient way of doing this than my example using the subquery as part of the where clause?
    Many thanks,
    Hazel
    Edited by: user11979866 on 04-Nov-2010 08:48

    Hazel:
    It would really depend on the sizes of the tables and the indexes available, but that is probably the way I would write it, at least as a first cut.
    You could lose the distinct in the in sub-query since it is implied by the in itself, and Oracle will only return one row from the sub-query for each value of dept in A.
    John

  • How to get Average of a column in UNION query

    Hi All,
    I will try to explain the issue as much as I can and If you need clarification on any piece please let me know.
    So, I have a Union Query with two sets of Criteria.
    The first Criteria Brings the list of Buildings and a set of Measures for it. The second criteria does the same but with a different set of filters.
    No I use a UNION between these both criteria and present them in a Pivot view so that we only have one row per each building. The values in each of the criteria in the UNION query are Summed
    Ex:
    Building
    Metric 1
    Metric 2
    1
    20
    30
    1
    25
    35
    2
    40
    50
    2
    45
    55
    So as I show in the pivot the result is
    Building
    Metric 1
    Metric 2
    1
    45
    65
    2
    85
    105
    Now the issue is with the Grand Total.
    I want the Grand Total to be an Average of the Buildings. So for Metric 1 The Grand Total should be (45+85)/2 because we have two buildings so the answer should be 65.
    How can I get that.
    Bottom Line: Need an Average as the Grand Total when the Aggregation rule on the column is set to Sum.
    we use 11.1.6.10 version

    Hi VJ
    What you are asking is impossible in the pivot table itself as you are asking one part of the pivot table to aggregate via one method, and another to aggregate via another method, on the same column ..
    It can be done using a calculated item. For your example above you'd use the formula ( $1 + $2) / 2.
    .. But thats HIGHLY explicit, and would only work if you KNOW how many buildings will come back in the query.. EVERYTIME.
    Why not restructure the query to combine it into a single query using an combinations of filters with OR in between?

  • Sum of columns in union query

    hi, i am using oracle 10g database..
    how to get the sum of column in union query ?
         select * from (select 100 records from dual), (select 50 available from dual)
    union
    select * from (select 200 records from dual), (select 150 available from dual)
    display should be like
                     records         available
                      100               50
                      200               150
    total            300               200thanks ...

    Peter vd Zwan wrote:
    try this:Grouping by records will not produce correct results:
    SQL> with a as
      2  (
      3  select * from (select 100 records from dual), (select 50 available from dual)
      4  union
      5  select * from (select 100 records from dual), (select 100 available from dual)
      6  union
      7  select * from (select 200 records from dual), (select 150 available from dual)
      8  )
      9  select
    10    case when grouping(records) = 0 then null else 'total' end tot
    11    ,sum(records)   records
    12    ,sum(available) available
    13  from
    14    a
    15  group by
    16  rollup (records)
    17  ;
    TOT      RECORDS  AVAILABLE
                 200        150
                 200        150
    total        400        300
    SQL> select  case grouping(rownum)
      2     when 1 then 'Total'
      3   end display,
      4          sum(records) records,
      5          sum(available) available
      6    from  (
      7            select * from (select 100 records from dual), (select 50 available from dual)
      8           union
      9            select * from (select 100 records from dual), (select 100 available from dual)
    10           union
    11            select * from (select 200 records from dual), (select 150 available from dual)
    12          )
    13    group by rollup(rownum)
    14  /
    DISPL    RECORDS  AVAILABLE
                 100         50
                 100        100
                 200        150
    Total        400        300
    SQL> SY.

  • Parameter in union query

    Hi Guys,
    I want to know how to create parameter in case of union query in 8.8. with new token option.
    Thanks Rashid

    Hi Rashid,
    It seems you are asking question regarding Crystal Report. Is that true?
    Thanks,
    Gordon

  • View using Union Query

    All,
    How to create a view using a union query in sql developer. I tried doing but when i check the syntax I got an error
    "The SQL syntax is valid, however the query is invalid or uses functionality that is not supported.
    Declarative query support does not currently include UNION, INTERSECT or MINUS"
    Could some one help me out
    Regards

    792011 wrote:
    All,
    How to create a view using a union query in sql developer. I tried doing but when i check the syntax I got an error
    "The SQL syntax is valid, however the query is invalid or uses functionality that is not supported.
    Declarative query support does not currently include UNION, INTERSECT or MINUS"
    Could some one help me outuse different/upgraded client since UNION is valid SQL

  • Prompts for Combine similar request (Union query)

    I have been given 5 tables for creating one report out of each table. I created aliases and
    necessary self joins. I now need a summaryreport that combines these five tables. I tried the
    "combine similar request" and the report functions fine. Now I have to create two prompts, one for
    country and one for job. These are fields available in 4 tables and have the same format alongwith
    the same datatypes. Please help me with this.
    Table 1 Report A
    Table 2 Report B
    Table 3 Report C
    Table 4 Report D
    Table 5 Report E
    Table 1 - Table 4 contains Country and Job field which is of the same format and datatype.
    Table 5 does not have these and its not necessary for us to prompt this.
    This has no star schema setup and I am not in a position to get it done as well. I considered each
    table to be a fact table and created aliases, selfjoins etc. Please help with the procedure to
    create the two dashboard prompts. If I choose USA then the first four amongst the union queries
    should reflect data for the USA. The same applies for Job.

    Hello
    Thanks for the reply.
    My problem here is that I have 5 different tables with country fields in them. They are of the same format and datatype but there is no join between these tables. If I choose one Country field from any particular table, then the combine similar request doesnt seem to take it for other queries where the fields come from a different table.
    eg.
    Table 1 - table 5 have country fields
    I choose to create a prompt based on Country from Table 1. The union query doesnt seem to reflect on filtering values on the queries from other tables. It would filter only the values from table 1.
    Please let me know as to what can be done!

  • Customised sub-total via UNION query - how to exclude from totals?

    Hi,
    I have a client requirement that a couple of companies have their own sub-total in a report, a treatment which applies to no other companies in their group.
    I have achieved this via a union all, but they also want a total of companies.
    Is there anyway to emulate a Grand Total, other than another union query such that the double count is not double counted?
    thanks for any ideas.
    Robert.

    only solution which i can think of is to create another union request for the grand total.. this way you wont add up your sub totals twice..

  • How do I make a 'union' query?

    Hi,
    How do I make a union query in JDev? Something like this.
    select 'x' from dual
    union
    select 'y' from dual;
    to get a rowsetinfo for showing in a combobox control? Don't ask
    me to create view in the database:-). It may not be practical for
    all such adhoc queries.
    --Gopal
    null

    Hi
    Sorry for that one. I didn't do my rtfm before asking that. There
    is a constructor for QueryInfo which takes any sql statement.
    --Gopal
    Gopal (guest) wrote:
    : Hi,
    : How do I make a union query in JDev? Something like this.
    : select 'x' from dual
    : union
    : select 'y' from dual;
    : to get a rowsetinfo for showing in a combobox control? Don't
    ask
    : me to create view in the database:-). It may not be practical
    for
    : all such adhoc queries.
    : --Gopal
    null

  • Create a Union query that automatically adds/contains new tables with a similar name

    Dear All, 
    For a research project i am upscaling from an Access database to SQL server/ SQL azure since the database got far too large. Now i am quite well known with Access, but to be quite honest, I am a SQL rookey. So a lot to learn for me here. 
    what I need is a union query that automatically adds new research dumps to the query. All research dumps have a table name starting with TD_EXP (Table Dump _ Export). In Access VBA I simply made a loop that builds up the SQL statement, but i have no clue
    how to do this within SQL Server...
    So, I need the UNION Query to select * from TD_Exp_2012_06_06_15_48 UNON all the  TD_Exp_XXXX_XX_XX_XX_XX that are added in the database,
    Who could help me out please with a dynamic SQL statement. 
    Best regards  Jurjen

    you can use INFORMATION_SCHEMA.TABLES view for that
    do like below
    DECLARE @Query varchar(max)
    SELECT @Query = STUFF((SELECT ' UNION ALL ' + 'SELECT * FROM ' + TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE 'TD_EXP%' FOR XML PATH('')),1,11,'')
    SELECT @Query
    Add one more condition as below if you want to exclude views from above 
    DECLARE @Query varchar(max)
    SELECT @Query = STUFF((SELECT ' UNION ALL ' + 'SELECT * FROM ' + TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE 'TD_EXP%' AND TABLE_TYPE = 'BASE TABLE' FOR XML PATH('')),1,11,'')
    SELECT @Query
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Trying to narrow down a UNIONed query

    I've compared 2 tables using MINUS. There should have been no difference. Since there was, I used UNION to display the corresponding rows between both tables. Now, in my result set, I have to search through many rows that don't have correspondents to find rows that do.
    Basically how do I narrow the UNION query down so that only the corresponding pair rows that have differences in their columns show up? I'm trying to use the primary key which is a combination of the first 5 columns. My query looks like this:
    select
    TRADE_DATE, ORDER_ROUTE_UID, ORDER_ENTRY_DATE, LEG_NBR, GROUP_SEQ_NBR,
    AFFL_FIRM_GROUP_ID, REC_CREAT_DATE
    from ors_firm_affl_hist@MSS_JOBS_HISTP01_LINK01.WORLD
    union
    select
    TRADE_DATE, ORDER_ROUTE_UID, ORDER_ENTRY_DATE, LEG_NBR, GROUP_SEQ_NBR,
    AFFL_FIRM_GROUP_ID, REC_CREAT_DATE
    from ors_firm_affl_hist;
    How can I use TRADE_DATE, ORDER_ROUTE_UID, ORDER_ENTRY_DATE, LEG_NBR, GROUP_SEQ_NBR in order to have the query display only the rows that have correspondents in the other table as opposed to rows that just aren't in either table?

    Not sure if this meets your requirements;
    SQL> with t1 as (
       select 'jon' first_name, 'smith' last_name, 'j' middle_init from dual union all
       select 'tom', 'a', 'a' from dual union all
       select 'bob', 's', 's' from dual union all
       select 'Stan', 'm', 'l' from dual union all
       select 'Kyle', 'b', 'r' from dual union all
       select 'Kenny', 'm', 'r' from dual union all
       select 'Eric', 'c', 'c' from dual),
         t2 as (
       select 'jon' first_name, 'smith' last_name, 'p' middle_init from dual union all
       select 'tom', 'a', 'l' from dual union all
       select 'bob', 's', 'j' from dual union all
       select 'Stan', 'm', 'l' from dual union all
       select 'Kyle', 'b', 'r' from dual union all
       select 'Kenny', 'm', 'r' from dual union all
       select 'Eric', 'c', 'c' from dual)
       select 'T1' source, first_name, last_name, middle_init from t1
       minus
       select 'T1' source, first_name, last_name, middle_init from t2
    union all
       select 'T2' source, first_name, last_name, middle_init from t2
       minus
       select 'T2' source, first_name, last_name, middle_init from t1
    order by 2,3,1
    SO FIRST LAST_ M
    T1 bob   s     s
    T2 bob   s     j
    T1 jon   smith j
    T2 jon   smith p
    T1 tom   a     a
    T2 tom   a     l
    6 rows selected.

  • Union query optimalization

    Help me please. I have this query with a Union
    select p.cdpwet, p.jaar, p.vnrproc
    from abgrp p,tbsltbetro bbt
    where p.vnrbslt = bbt.vnrbslt
    and bbt.cdsrt like :n_rol
    and bbt.nrbetr in (select i.nrbetr from tuser i
    where i.naam like :n_naam
    and (i.cdsrtrpers like :n_cdsrtrpers
                   or :n_cdsrtrpers is null)
    and :n_nrbetr is null
    and i.indsrtpers = 'R'
    union
    select to_number(:n_nrbetr)
    from dual
    where :n_nrbetr is not null)
    I will the same result but without a Union.
    Regards,
    Patrick

    Hi Patric,
    probably if you dont want to display UNIQUE values and you are sure that both parts of your query will give different o/p and you just want to club them.. Use UNION ALL.. Your performance problem will be solved, especially when the data fetched is large. Union finds the two data sets and try to sort them to display UNIQUE records only where as UNION ALL just merges them so saving time on sorting.
    Hope that this will help you.
    Regards
    Santa

  • How to enhance the following query?

    Hi all,
              I am using the following piece of code to some fields from table STAS.However this query is taking a long time to execute.
    Can anyone please tell me how can i enhance it so that it may execute faster?Thnx in advance.
    LOOP AT IT_FG WHERE STLAL = ' '.                                   
      SELECT STLAL FROM STAS
      INTO IT_FG-STLAL
      WHERE STLNR = IT_FG-STLNR
        AND STLKN = IT_FG-STLKN.                                         
      MODIFY IT_FG.                                                    
      ENDSELECT.                                                       
    ENDLOOP.
    Regards,
    S.choudhury.
    Edited by: Rob Burbank on Dec 23, 2009 12:02 PM

    The above recommendation are only o.k., if you use sorted tables. However, maybe people don't mention because you should always use sorted tables. I am joking, but the recommendation is true!
    Otherwise use binary search, but better use sorted tables!
    And for the loop you should use ASSIGNING which speeds up the modify.
    field-symbols: <fs>   type it_fg.
    SELECT STLAL STLNR STLKN
                  INTO table IT_new
                  FROM STAS
                  for all entries in  IT_FG
                  WHERE STLNR = IT_FG-STLNR
                  AND STLKN = IT_FG-STLKN.
    SORT it_new BY stlnr stlkn.
    LOOP AT IT_FG ASSIGNING <fs>
              WHERE STLAL = ' '.
         read table  IT_new 
                 into wa_new
                 WITH KEY STLNR = IT_FG-STLNR
                  AND STLKN         = IT_FG-STLKN
                 BINARY SEARCH.
    * type ???.
          <fs> = wa_new-STLAL.
    ENDLOOP.

  • Can we change filter column values in a union query using Dashboard prompt

    Hi,
    I have a requirement in which have to draw a chart report for last six months?.
    When i query against database, my query got different where clause for open month and close month.
    Say for july month bar, it got close month as july and open month as july, june, may. Like this, for june month bar, it has to have close month as june and open month as june, may, april. like this, i created six union queries using repository variable.
    Want to give control using dashboard prompt for close month and open month?
    my query look like this.
    select close month1, fact1 from table1
    where close month = july and open month in (july, june, may)
    UNION
    select close month2, fact2 from table1
    where close month = june and open month in (june, may, april)
    UNION
    select close month3, fact3 from table1
    where close month = may and open month in (may, april, march)
    UNION
    select close month4, fact4 from table1
    where close month = april and open month in (april, march, february)
    UNION
    select close month5, fact5 from table1
    where close month = march and open month in (march, february, january)
    UNION
    select close month6, fact6 from table1
    where close month = february and open month in (february, january, december)
    Welcome your suggestions on this?.
    Thanks

    Hi Karol,
    Yes the prompt is working fine when i put this following method under the "Button" Component.
    APPLICATION.openPromptDialog(800, 600);
    Somehow the when i use the "Input Field" and use the "Button" Component and write this following logic inside it i don't see the prompt is not taking the values what i am entering in input field i assume that its issue with data-source not getting refreshed.
    Variable=INPUTFIELD_1.getValue();
    APPLICATION.setVariableValue("PercentageIncrease",Variable);
    Thanks,
    Kumar

  • Discoverer Date Range Union Query

    Hi All,
    I need your help in creating a discovere report in version 11G.
    Following Report find missing elimination account based on Transaction done in a date Range. Find out how many accounts are not defined in Elimination Account Setup. Following query gives me desired output but i am having hard time creating a discoverer report for Date Range Parameter as Date Range only applied to one side of union.
    In First Query i used decode with sysdate itself so that i can use effective_date as parameter and second side i just kept sysdate.
    PLease let me know how can i create a parameterized report for effective_date range.
    SELECT
        /*+ ORDERED
        USE_NL(jel jeh jeb cat src)
        INDEX(jel GL_JE_LINES_N1)
        INDEX(jeh GL_JE_HEADERS_U1)
        INDEX(jeb GL_JE_BATCHES_U1)
        INDEX(cat GL_JE_CATEGORIES_TL_U1)
        INDEX(src GL_JE_SOURCES_TL_U1) */
        CC.SEGMENT1
        ||'.'
        ||CC.segment2
        ||'.'
        ||CC.segment3
        ||'.'
        ||cc.segment4
        ||'.'
        || cc.segment5
        ||'.'
        || cc.segment6 Account,
        decode(sysdate,sysdate,sysdate,jel.effective_date) trx_date
      FROM gl_code_combinations cc,
        gl_je_lines jel,
        gl_je_headers jeh,
        gl_je_batches jeb,
        gl_je_categories cat,
        gl_je_sources src
      WHERE cc.CHART_OF_ACCOUNTS_ID = 50308
      AND cc.segment2              IN ('111710','201910')
      AND jel.code_combination_id   = cc.code_combination_id
      AND jel.status
        || ''                = 'P'
      AND (jel.accounted_cr != 0
      OR jel.accounted_dr   != 0)
      AND jeh.je_header_id   = jel.je_header_id
      AND jeh.actual_flag    = 'A'
      AND jeh.currency_code       != 'STAT'
      AND jeb.je_batch_id          = jeh.je_batch_id
      AND jeb.average_journal_flag = 'N'
      AND src.je_source_name       = jeh.je_source
      AND cat.je_category_name     = jeh.je_category
      and jel.effective_date between to_date('01-JAN-2011','DD-MON-RRRR') and to_date('31-MAY-2011','DD-MON-RRRR')
      MINUS
      SELECT (source_segment1
        ||'.'
        ||source_segment2
        ||'.'
        ||source_segment3
        ||'.'
        ||source_segment4
        ||'.'
        ||source_segment5
        ||'.'
        ||source_segment6) def_acnt,
        sysdate
      FROM GL_ELIM_ACCOUNTS_MAP

    Hi,
    You can use the following SQL to get the effective date into the SQL and by that create the condition in the report:
    SELECT
    CC.SEGMENT1
    ||'.'
    ||CC.segment2
    ||'.'
    ||CC.segment3
    ||'.'
    ||cc.segment4
    ||'.'
    || cc.segment5
    ||'.'
    || cc.segment6 Account,
    decode(sysdate,sysdate,sysdate,jel.effective_date) trx_date,
    jel.effective_date
    FROM gl_code_combinations cc,
    gl_je_lines jel,
    gl_je_headers jeh,
    gl_je_batches jeb,
    gl_je_categories cat,
    gl_je_sources src
    WHERE cc.CHART_OF_ACCOUNTS_ID = 50308
    AND cc.segment2 IN ('111710','201910')
    AND jel.code_combination_id = cc.code_combination_id
    AND jel.status
    || '' = 'P'
    AND (jel.accounted_cr != 0
    OR jel.accounted_dr != 0)
    AND jeh.je_header_id = jel.je_header_id
    AND jeh.actual_flag = 'A'
    AND jeh.currency_code != 'STAT'
    AND jeb.je_batch_id = jeh.je_batch_id
    AND jeb.average_journal_flag = 'N'
    AND src.je_source_name = jeh.je_source
    AND cat.je_category_name = jeh.je_category
    AND NOT EXISTS (
    SELECT 1
    FROM GL_ELIM_ACCOUNTS_MAP
    WHERE CC.SEGMENT1 = source_segment1
    AND CC.segment2 = source_segment2
    AND CC.segment3 = source_segment3
    AND cc.segment4 = source_segment4
    AND cc.segment5 = source_segment5
    AND cc.segment6 = source_segment6
    AND decode(sysdate,sysdate,sysdate,jel.effective_date) = SYSDATE
    *** I removed the hints, but if you need those get them back
    *** BTW i didn't understand the logic behind the "decode(sysdate,sysdate,sysdate,jel.effective_date)" wouldn't it always be SYSDATE???
    Tamir

Maybe you are looking for