set of results based on condition

Hi all

I have a requirement that contains three conditions which means my final result set is derived
3 different conditions.
I have three tables and I Union to get the result set.
ex:
 Select cust_id, cust_name , cust_add, 'A' condition  
            From  Table1 {CODE}
         union
            Select cust_id, cust_name , cust_add, 'B' condition
              From  Table2
         union
            Select cust_id, cust_name , cust_add, 'C' condition
              From  Table3                                                         
   Values are:
               cust_id           cust_name                cust_add           condition
                 100               roy                       ABC                   A
                 100               roy                       ABC                   B
                 101               eddy                                            C
                 102               pat                                             B
                 102               pat                                             C
Instead of having the same information on two different lines, I want to have the same line with 2 another column showing what conditions he met.
   i require values like this:
                cust_id           cust_name               cust_add           condition1          condition2        condition3
                 100               roy                       ABC                   A                   B
                 101               eddy                                            C
                 102               pat                                             B                   C
Can someone help me to achieve this type of result set.
Thank you!

Hello

This is called a pivot

WITH     union_query     AS
(
     Select cust_id, cust_name , cust_add, 'A' condition
            From  Table1 {CODE}
         union
            Select cust_id, cust_name , cust_add, 'B' condition
              From  Table2
         union
            Select cust_id, cust_name , cust_add, 'C' condition
              From  Table3
)
,     got_rnum     AS
(
     SELECT     union_query.*
     ,     ROW_NUMBER () OVER (PARTITION BY cust_id)     AS rnum
     FROM     union_data
)
SELECT       cust_id,      cust_name,     cust_add
,       MAX (CASE WHEN r_num = 1 THEN condition END)     AS condition1
,       MAX (CASE WHEN r_num = 2 THEN condition END)     AS condition2
,       MAX (CASE WHEN r_num = 3 THEN condition END)     AS condition3
FROM       got_rnum
GROUP BY  cust_id,      cust_name,     cust_add
ORDER BY  cust_id,      cust_name,     cust_add;

It's a bit more complicated than some points of articulation, because there is nothing in your raw data that tells you which column of output directly each condition belongs in. (in other words, for the results you requested, a 'C' could go to condition1 or condition2 and condition3: just by looking at the line with the 'C' we cannot tell who.) We do this by using the function ROW_NUMBER analytic, and, like a lot of things involving analytic functions, which requires a separate subquery.

Tags: Database

Similar Questions

  • Get the next row in the set of results under certain conditions

    Hello
    I have a result set with a column in ascending order of the numbers. Now, I want to compare these numbers to a value. If one of the numbers exactly matches the value then all is well and I use number < = value as a condition. If the value does not match exactly I want to get the next number in the result as well. A short example

    NB in resultset
    41
    82
    123
    164
    205
    246

    To compare with value = 200, I want to have

    41
    82
    123
    164
    205

    as a result.

    To compare with value = 164, I want to have

    41
    82
    123
    164

    Thanks for any advice.
    Carsten cordially

    You can use analytical functions for that. There are several options, here is one.

    with testdata as (select 41 num from dual union all
                      select 82  num from dual union all
                      select 123 num from dual union all
                      select 164 num from dual union all
                      select 205 num from dual union all
                      select 246 num from dual)
    /* end of test data creation */
        ,resulttab as (select num, nvl(lag(num) over (order by num) ,0) next_num
                       from testdata )
    select num
    from resulttab
    where next_num < 200 ;
    NUM
    ---
    41
    82
    123
    164
    205
    
    ...
    select num
    from resulttab
    where next_num < 164 ;
    41
    82
    123
    164
    
  • You have reached the maximum of pages in this set of results of content. If you are looking for something specific, try applying a filter of content type or enter a search term.

    I get error frequently below.  In General, when you navigate on old posts on the forum SQL and PL/SQL, after reading a post, I click on the left arrow in my Firefox browser, which I expect to take me to the page of the posts that I had.  Instead, I get a page with no messages.  I then click on a forum page numbers in the upper right corner.  Sometimes brings back me to the page that displays the list of the posts that I had.  However, more often I get the below error.  So try to navigate from one position to another is desperately slow.  You can fix this?  Everybody brings a work around to be able to get from one station to another, or at least back to old messages without the error page?  This is a problem that happened before and after the upgrade.

    "You have reached the maximum of pages in this set of results of content. If you are looking for something specific, try applying a filter of content type or enter a search term. »

    Have you tried right-click (ctrl-click on Mac) and choose 'Open link in a new tab' instead? With all the dynamic html today browser back and before options are often dead still. If you open links in a new tab or window, you can simply close the window instead of using the back button. It may take awhile to get used to it, but there are some benefits, such as the loading of the pages in the background, and you do not lose the focus of the page where you. You can disable "when I open a link in a new tab, swtich it immediately." If I understand your problem, maybe it works better.

  • Based where conditional clause...

    dear team,
    i have following code..
    
    Declare
      gv_flag1 Varchar2(1)   := 'N';
      gv_flag2 Varchar2(1)   := 'N';
      gv_flag3 Varchar2(1)   := 'N';
      all_where1       Varchar2(250);
      all_where2       Varchar2(250);
      ALL_where3       Varchar2(250);
      V_QTY           Number;
    Begin
      If gv_flag1 = 'N' Then
         all_where1 := 'AND '||'V.OWNER = ''PROD''';
      End If;
      DBMS_OUTPUT.PUT_LINE(all_where1);
      
      If gv_flag2 = 'N' Then 
         all_where2 := 'AND '||'V.OPERATION NOT LIKE (''10%'')';
      End If;   
      DBMS_OUTPUT.PUT_LINE(all_where2);
      
      If gv_flag3 = 'N' Then
         all_where3 := 'AND '||'V.OPERATION NOT LIKE (''07%'')';
      End If;
      DBMS_OUTPUT.PUT_LINE(all_where3); 
       
      --select based on conditions..
    End; 
    
    NOW I want where conditions in select statment to be conditional...
    
    which means if flag1='N' and flag2 = 'N' then use both all_where1 and all_where2 in *where* clause statement...
    if flag1='N' and flag3 = 'N' then then use all_where1 and all_where 3 in *where* clause of select statement...
    if all there flag = 'N' then use all_where conditions in *where* clause of select statement...
    
    i have 3 flags, which means total of 9 combinations,  is there any simpler way to do such kind of thing??
    
    please assist me
    
    nic

    Nicloei W wrote:
    Hi Jeenesh,

    What happens if Flag2 = 'Y' and Indicateur3 = 'Y' in this case, I want only the condition with Flag1

    concerning
    NIC

    SQL> ed
    Wrote file afiedt.buf
    
      1  Declare
      2    gv_flag1 Varchar2(1)   := 'N';
      3    gv_flag2 Varchar2(1)   := 'Y';
      4    gv_flag3 Varchar2(1)   := 'Y';
      5    --all_where1       Varchar2(250);
      6    --all_where2       Varchar2(250);
      7    --ALL_where3       Varchar2(250);
      8    lc_query varchar2(1000):= 'select count(*) from test v ';
      9    lc_where varchar2(500) := ' where 1 = 1 ';
     10    V_QTY           Number;
     11  Begin
     12    If gv_flag1 = 'N' Then
     13       lc_where := lc_where||' AND V.OWNER = ''TEST''';
     14    End If;
     15    If gv_flag2 = 'N' Then
     16       lc_where := lc_where||' AND V.OPERATION NOT LIKE ''10%''';
     17    End If;
     18    If gv_flag3 = 'N' Then
     19       lc_where := lc_where||' AND V.OPERATION NOT LIKE ''07%''';
     20    End If;
     21    lc_query := lc_query||lc_where;
     22    dbms_output.put_line(lc_query);
     23    dbms_output.put_line('-----------');
     24    execute immediate lc_query into v_qty;
     25    dbms_output.put_line('Count: '||v_qty);
     26* End;
    SQL> /
    select count(*) from test v  where 1 = 1  AND V.OWNER = 'TEST'
    -----------
    Count: 3
    
    PL/SQL procedure successfully completed.
    
  • Query to get the data of the column and the metadata in the same set of results.

    Is it possible to build a query to get the values of the columns in a table and also be able to get some metadata (data type, data_length, data_precision, data_scale) for columns in the same set of results.

    If I use a join, have a common value to join on the two tables?

    you use a cross join, not requiring common values.

    create table T (n number, d date, v varchar2(30));
    insert into T values (1,sysdate,'ABC');
    commit;
    
    select C.column_name, c.data_type, c.data_length,
    case c.column_id
     when 1 then to_char(T.N)
     when 2 then to_char(T.D)
     when 3 then T.V
    end VALUE
    from USER_TAB_COLUMNS C, T
    where C.table_name='T'
    order by c.column_id;
    
  • Total amount and are rotating back in the same set of results

    I want to return a set of results in the following format:
    YEARMONTH Total ModelA ModelB ModelC
    200101    0     0      0      0
    200102    10    5      5      0
    200103    8     2      2      4
    where the total amount is the sum of the hours for all types of models grouped by yearmonth and columns of each model are the sum of hours per type of model grouped by yearmonth. I can get the correct results with the following query selects nested:
            select distinct yearmonth,
         sum(a.hours) as Total,
         (select sum(b.hours) from model_hours b
             where model = 'ModelA' and a.yearmonth = b.yearmonth) as ModelA,
            (select sum(b.hours) from model_hours b
             where model = 'ModelB' and a.yearmonth = b.yearmonth) as ModelB,
            (select sum(b.hours) from model_hours b
             where model = 'ModelC' and a.yearmonth = b.yearmonth) as ModelC
        from model_hours a
        group by yearmonth
        order by yearmonth
    I was curious to try use the pivot function in Oracle 11 to get the same results and I am able to get all the results, EXCEPT the total number of hours by using the following query:
        select * from (
             select yearmonth, hours, model
             from model_hours a
        )
        pivot
        ( 
             sum(hours)
             for model in ('ModelA', 'ModelB', 'ModelC')
        )
        order by yearmonth
    which returns this result:
    YEARMONTH  ModelA ModelB ModelC
    200101     0      0      0
    200102     5      5      0
    200103     2      2      4
    I was not able to understand how to get the sum of hours for all models, grouped by yearmonth, in this result set also. Is this possible? And if yes, isn't - that's likely to be more effective than selects it nested? This particular table has some 200K lines right now.

    Hello

    As far as I know, the Oracle 11 SELECT... PIVOT function only works on mutually exclusive groups.
    You can derive the total revolving data, like this:

    WITH        pivoted_data          AS
    (
         select  *
         from      (
                           select  yearmonth, hours, model
                    from    model_hours a
                  )
             pivot
              (
                      sum(hours)
                      for model in ( 'ModelA'     AS modela
                                   , 'ModelB'     AS modelb
                         , 'ModelC'     AS modelc
                         )
                  )
    )
    SELECT       yearmonth
    ,       modela + modelb + modelc     AS totla     -- may need chnaging if values can be NULL
    ,       modela, modelb, modec
    FROM       pivoted_data
    ORDER BY  yearmonth
    ;
    

    Published by: Frank Kulash, 26 March 2012 15:01

  • Comparing the 2 sets of results

    Hello

    I compare the 2 sets of results and determine if they are identical.

    Queries are:

    SELECT CARRIER_ID, ROUTE_POSITION
    OF ROUTE_WG_PHASE4

    SELECT CARRIER_ID, ROUTE_POSITION
    OF ROUTE_WG_PHASE3

    I tried to use less, but it does not work when the first result set has fewer than the second record.

    Oracle 10g

    Thank you

    In general, you can do something like

    (
    SELECT CARRIER_ID,ROUTE_POSITION , 'In 4 and not 3' desc
      FROM ROUTE_WG_PHASE4
    MINUS
    SELECT CARRIER_ID,ROUTE_POSITION , 'In 4 and not 3' desc
      FROM ROUTE_WG_PHASE3
    )
    UNION ALL
    (
    SELECT CARRIER_ID,ROUTE_POSITION , 'In 3 and not 4' desc
      FROM ROUTE_WG_PHASE3
    MINUS
    SELECT CARRIER_ID,ROUTE_POSITION , 'In 3 and not 4' desc
      FROM ROUTE_WG_PHASE4
    )
    

    According to the specificity of your data, you can also just add a COUNT (*) () to each query and a single NEGATIVE sign.

    Justin

  • How to filter through a set of data based on user input

    Hi all

    I'm trying to filter through a set of data, purchase only the files that meet the requirements of users.

    I ask the user to enter three different values, one for a frequency to start another for a frequency of end and also the value of the rated power.

    The way I am filtering from now thanks to this data set is using a function called the regular expression function as well as the analysis of string function to break up the name of file and data digital take-away, then compare these data on the entries of users.

    These values that meet the conditional statement will be sent to a ring of results for a user to go through.

    For now, I filled it is not as much functionality in this method, the user must be very careful in the way which he or she saves files and my program may work correctly.

    I am ataching a photo of this part of the program.

    Thanks for the help.

    I think that my second statement should check on a white paper OR PDM.  Have you noticed the color?  This is a clickable link.  If you read the material here, it should clear up confusion in the first part of my post.

    I have a colleague who, like you, encodes the parameters of the study of the (very long) string of the name of the file.  I always shout at him about it, because it requires him (because you are considering do) build routines for (a) analyzes the names (to retrieve the information hidden in them), (b) to organize the data in a form of "LabVIEW Database" and then (c) figure out how (in LabVIEW) for write "queries" on this database.  More file names are not particularly easy for a human to read, are extremely long and invite more mischief (have you thought about putting your files in folders which are similarly 'file-information-coded'?  Becomes even more messy more fast).

    You might think Oh, "it's too late to make a change, I have already all of these data", but what good is it if you can't analyze easily, group them, sort, etc. ?

    Bob Schor

  • Groovy aggregate function based on condition

    Hi all

    I use jdev 12.1.3.0.0

    I've set up an aggregate function in my master EO as explained in the blog

    https://blogs.Oracle.com/ADF/entry/using_groovy_aggregate_functions_in

    I need to add a condition to the number of records based on an attribute of the object of details view. Algorithm for the use case is

    detailsAccessor.count ("SmsId")

    where detailsAccessor.MessageType is equal to "file."

    Could you help me write an expression to achieve this functionality.

    Thank you

    Mozakkir

    All aggregate in groovy functions accept a groovy as a parameter expression.

    So instead of detailsAccessor.count("SmsId") you can try something like: detailsAccessor.count ("MessageType is 'Applicant'")

    Or convert sum() like this: detailsAccessor.sum ("MessageType is"Applying"? 1: 0 ")"

    Dario

  • Chronology of trigger has to play based on conditional

    I'm working on a project in which I have four draggables, able to receive four and four default droppable in the composition.  Once these four individual draggables were abandoned on the beneficiaries of their point of view I want to trigger a symbol to play his chronology based on a conditional statement that checks that all four draggables were deleted correctly.

    To do this, I pushed the four movable in a table after groups that they were interrupted and movable destroyed using the jquery ui library.  I know that the table is filled because I get the appropriate groups in the console and the length of the table.

    I tried to make a loop for to analyze the table and feed than an if statement to verify that it has four points and trigger the chronology of symbol reading.  Only problem is that it doesn't.  Do you have advice on how to solve the problem of the code below?

    correct=[];

    //DRAGGABLE RIDE TO AIRPORT GROUP

    sym.$('rideGroup').draggable({           containment:'parent',           scope: 'task3',           opacity:.9,            revert:'invalid',            zIndex:6 });

    //Make the targetRide area droppable and accept the Ride to Airport Group

    sym.$('targetRide').droppable({

          scope:'task3',

          drop: function(event, ui){

               accept: 'rideGroup'

               tolerance:'fit'

               draggable:'destroy'

               correct.push('rideGroup');

          }

    });

    sym.$('defaultRide').droppable({

          scope: 'task3',           drop: function(event,ui){

               accept: 'rideGroup'

               }

         });

    for(var i=0; i <= correct.length; i++){

          if(i === 4 && correct.length === 4){

               sym.getSymbol('Animation').play('greatJob');

          }else{           sym.getSymbol('Animation').play('notRight');

       }

    };

    If I take the line code sym.getSymbol in the conditional statement and place it where the push instruction has, each of the draggables play the timeline after a fall.  We're not that good.  We have the timeline plays that once all four of the draggables were dropped.  I've included the code for one of the moveable and sets able to receive here for reasons of space only.

    Thanks for any help you can provide.

    K lies in case handler - so when the event occurs, k is incremented and when it equals the number of events (the draggables that are well placed) it does what you want it to do, in this case an animation. This could be used for something else if you wanted to.

    The position can use left, high, mid, low, Center... I would not add pixels to it. It is best to get the placement in this way. If you have images that have limits of the strange, you could use transparent droppable on images. Hope it makes sense.

  • Area text entry - different results based on different inputs?

    Hello

    I am trying to find a way to use the text input box (if there is a better tool for go, let me know) in order to show a particular legend with a particular response box. Thus, for example, in a text entry box standard, I have listed 4 possible "correct" answers, and for this example, I'll just say answer 1, answer 2 and answer 3 answer 4. I would like every answer to bring up a box of different caption with a different statement based on what answer they type in. Basically:

    Response-> Caption 1

    Answer 2-> Caption 2

    etc.

    All I ever get is for each right answer answer the same standard buttons, success, failure, etc.. I can't add a new button that would pop as the standard, or, as I would prefer, legends instead. Any ideas?

    You should be able to do it with a tip action.

    Create captions that you want to display for each variable and uncheck the "visible" box for each.

    Disable the button for the ETB.  Add a separate button and set the "success on ' to execute advanced action.  Create a conditional action that checks if the variable associated with the ETB and shows the legend you want based on the variable.

    The way I tested it, I had an 'if' statements for each variable.

  • How to change the color of line based on Condition

    Dear all,

    We have requirment as shown below

    Based on the condition, I want to show the color for all of the line

    Example of

    If attribute = 'Y' then
    {
    < show the color for complete line in advanced table?
    }

    Please give me suggestion how join my requirment.

    Thank you
    Venkat Reddy Pulichintha

    Hey...

    you said that the code you wrote is working for a column... in the same way you can set the CSS Style on all other columns as well...

    Why don't you go with code that works...

    DataBound APIs are an alternative solution to this... you can search on it later...

    Thank you
    Gerard

  • Programmatically set the result expression of filtering

    Hi all

    Is it possible to set configuration > Report Options > Expression of filtering results by program?

    I am developing a custom step framework, so I would do this without a reminder of movie file.

    Thanks in advance.

    Kind regards

    ACE

    You can access the filter expression via RunState.Root.Locals.ReportOptions.ResultFilterExpression from anywhere in your sequence.

    -Jack

  • Get-advancedsetting showing only a limited set of results

    Hi all

    I'm very new to using PowerCLI, so please be patient with me.

    I am trying to determine which of our virtual machines have the Advanced setting "device.hotplug" 'true '.

    I think I got the script to do so, the only question is, is not producing the expected results.

    When you run a command that does not filter results, it only returns results for 40 VM, when I expect to slightly more than 200.

    This is the command that I expect the return value for each virtual machine in a cluster:

    Get-Cluster-name of the "cluster" | Get - vm | Get-AdvancedSetting - name devices.hotplug | Format-Table-entity property, Name, Value - AutoSize

    I get a complete list of virtual machines, when I run:

    Get-Cluster-name of the "cluster" | Get - vm

    That should be all that you need to see my problem, however, for good measure and any comment, here is the little script I'm working on the only exit from the virtual computer with the "device-hotplug" setting enabled. Feedback or comments welcome.

    $hosts = get-cluster-name of the "cluster" | Get - vm |

    Where-Object {$_ .name-notlike 'exclude'}

    }

    $results = {foreach ($vihost in $hosts)

    Get-vm-name $vihost | Get-advancedsetting - name devices.hotplug |

    Where-Object {$_.} Value - notlike 'false'}

    }

    $results | format-table-entity property, Name, Value - AutoSize

    See you soon

    Lloyd

    Make sure that each VM has who progress together setting?

    Try like this, it should return all the virtual machines, also those who does not have the setting

    Get-Cluster-name "group" | Get - VM |

    Select Name,@{N='device.hotplug'; E={$_ | Get-AdvancedSetting - name devices.hotplug | Select value - ExpandProperty}}

  • display value based on condition

    Hi all

    Do not know if my subject is the most descriptive, but don't know how to explain in a sentence.

    I have wells that may have several statutes (one record for each State). I need to create a column to display a Y or N from or not a given wells has only certain articles types. If all the records of a given good Susp or Abd, so I want to display a Y. If good records include Susp or Abd, but also the other articles (or do not even have a status of susp or abd) so I want to display a N.

    So:
    Well           Status       ident
    12345         SUSP          Y
    12345         SUSP          Y
    12345         ABD           Y
    98765         SUSP          N
    98765         PROD         N
    98765         ABD           N 
    45678         SUSP          Y
    45678         SUSP          Y
    ASDFG         ABD           Y
    ASDEG         ABD           Y
    TTTTT         PROD       N
    TTTTT         TEMP       N
    Any thoughts?

    Published by: dgouin on December 13, 2012 06:59

    Hello

    Here's one way:

    SELECT     well, status
    ,     CASE
             WHEN  EXISTS (
                              SELECT  1
                        FROM    table_x
                        WHERE   well     = m.well
                        AND     NVL ( status
                                        , '?'
                              )     NOT IN ('SUSP', 'ABD')
                          )
             THEN  'N'
             ELSE  'Y'
         END     AS ident
    FROM     table_x  m
    ;
    

    Another way uses analytical functions:

    SELECT     well, status
    ,     MIN ( CASE
                   WHEN  status IN 'SUSP', 'ABD')
                THEN  'Y'
                ELSE  'N'
               END
             ) OVER (PARTITION BY well)     AS ident
    FROM     table_x
    ;
    

    This 2nd request is based on the fact that "n" comes before "Y" is sort of chain order. If you use other symbols, such as 'J' and ' n ", then you may need to use MAX instead of MIN above."

    I hope that answers your question.
    If not, post a small example data (CREATE TABLE and only relevant columns, INSERT statements) for all of the tables involved and also publish outcomes from these data.
    Explain, using specific examples, how you get these results from these data.
    Always say what version of Oracle you are using (for example, 11.2.0.2.0).
    See the FAQ forum {message identifier: = 9360002}

Maybe you are looking for