Percentage calculation in t-sql based on two columns

Hi All
I have a source table with 4 columns and data like this..
ID  Cnt   Col1   Col2 
1    22    17      5   
2    20    15      5   
3    12    5       7   
4    10    null    10    
5    25    25      null   
My output should look like this..
ID  Cnt    Col1   Col2  Col1%   Col22%
1    22    17        5      77.27    22.73
2    20    15        5      75.00    25.00
3    12     5         7      41.66    58.34
4    10               10      0          100
5    25    25                100        0
Create Statement:
CREATE TABLE [dbo].[Sample] (
 [ID] Int NOT NULL,
 [Cnt] Int NULL,
 [Col1]  Int NULL,
 [Col2]  Int NULL,
 CONSTRAINT [Sample] PRIMARY KEY CLUSTERED
 [ID] ASC
Insert Statement:
insert into Sample(ID, cnt,Col1, col2) values (1 ,   22  ,  17   ,   5 )  
insert into Sample(ID, cnt,Col1, col2) values (2 ,  20  ,  15    ,  5   )
insert into Sample(ID, cnt,Col1, col2) values (3 ,   12  ,  5    ,   7 )
insert into Sample(ID, cnt,Col1, col2) values (4 ,   10  ,  null ,   10 )
insert into Sample(ID, cnt,Col1, col2) values (5 ,   25 ,   25   ,   null)
Right now I am using below SQL but % fields are not coming correct.
Select (COUNT(CASE WHEN (col1-col2)) < 1) THEN -1  END)  /COUNT(*) * 100) AS Col1%
,(COUNT(CASE WHEN (col1-col2) >=1) THEN  1  END)  /COUNT(*) * 100) AS Col2%
I need SQL to get correct values in col1% and col2%
Thanks,
RH
sql

Is it what you need:
SELECT Id
,cnt
,col1
,col2
,CASE
WHEN Col1 IS NULL
OR Col1 = 0
THEN 0
ELSE CAST((col1 * 100.0) / cnt AS DECIMAL(10, 2))
END AS [Col1%]
,CASE
WHEN Col2 IS NULL
OR Col2 = 0
THEN 0
ELSE CAST((col2 * 100.0) / cnt AS DECIMAL(10, 2))
END AS [Col2%]
FROM Sample
For every expert, there is an equal and opposite expert. - Becker's Law
My blog
My TechNet articles

Similar Messages

  • Update column based on two columns

    Hi,
    MinValue     MaxValue    Desc
    -1                -1    
    -1                 1    
    -1                 2    
    0                  0    
    0                  1    
    0                  2 
    The above is my table which is having three columns MinValue, MaxValue, Desc. First two columns have data and I need to update the 3rd column 'Desc' based on two columns data.
    I need to update like,
    when MinValue=-1 and MaxValue=-1 then 'NotSpecified'
    when MinValue=-1 and MaxValue=1 then 'Up to 1'
    when MinValue=-1 and MaxValue=2 then 'Upto 2'
    when MinValue=0 and MaxValue=1 then 'At lest 1'
    when MinValue=0 and MaxValue=2 then 'At least 2'
    when MinValue=0 and MaxValue=3 then 'At least 3'
    The data in 'MaxValue' is like 1,2,3,4,5...50. So for each description it should append this value as mentioned above(till 'Up to 50', 'At least 50'). How can I do this with case statement?
    Thanks,
    Gangadhar

    declare @T table ( MinValue int,MaxValue int, [Desc] nvarchar(100) );
    insert @T ( MinValue, MaxValue )
    values ( -1, 1 ) , ( -1, 1 ) , ( -1, 2), ( 0, 0), ( 0, 1), ( 0, 2)
    select *
    from @T
    update @T
    set [Desc] = case
    when MinValue=-1 and MaxValue=-1 then 'NotSpecified'
    when MinValue=-1 and MaxValue=1 then 'Up to 1'
    when MinValue=-1 and MaxValue=2 then 'Upto 2'
    when MinValue=0 and MaxValue=1 then 'At lest 1'
    when MinValue=0 and MaxValue=2 then 'At least 2'
    when MinValue=0 and MaxValue=3 then 'At least 3'
    end
    select *
    from @T
    T-SQL Articles
    T-SQL e-book by TechNet Wiki Community
    T-SQL blog

  • Sorting based on two columns in report

    Hi,
    we have one issue on sorting based on two columns in report.
    In the report we are doing sorting on two columns(week_id and stage_name). I have attached the screen shot for the same. The sorting is first done on the week_id and then on the stage_name. The issue comes when we have no data for the stage 1 - Prospect in W1. The stage goes to the second position.
    Please suggest if there is any work around to show the 1 - Prospect stage in W1.
    Regards,
    Ambika Nanda.

    what is w1? where is screenshot? and is stage seoncd sort? if so what is the issue?

  • Unique row based on two columns and single column

    Dear Members,
    I have a table which contains duplicate rows, for which a query should be able to fetch the unique row from the table. Here the unique is not based on one column, but it should be on two columns and also check for uniqueness on one column.
    create table addr ( firstname varchar2(10), lastname varchar2(10), area varchar2(3));
    insert into addr values('bob', 'james', '1');
    insert into addr values('bob', 'james', '1');
    insert into addr values('harry', 'bert', '1');
    insert into addr values('jimmy', 'bert', '1');
    insert into addr values('sam', 'mac', '1');
    insert into addr values('sam', 'knight', '1');
    insert into addr values('tom', 'sand', '1');
    insert into addr values('cat', 'mud', '1');
    The output of query should contain 3 rows.
    bob - james
    harry - bert or jimmy - bert [ either one of them, but not both ]
    sam - mac or sam - knight [ either one of them, but not both ]
    tom - sand
    cat - mud
    SELECT firstname, lastname as total from addr WHERE area = '1' GROUP by firstname,lastname; This does not take of single column duplication..
    Any suggestions..

    SQL> with t_data
    as
    select 'bob' as firstname, 'james' as lastname, '1' as area from dual union all
    select 'bob', 'james', '1' from dual union all
    select 'harry', 'bert', '1' from dual union all
    select 'jimmy', 'bert', '1' from dual union all
    select 'sam', 'mac', '1' from dual union all
    select 'sam', 'knight', '1' from dual union all
    select 'tom', 'sand', '1' from dual union all
    select 'cat', 'mud', '1' from dual
    SELECT
            firstname,
            lastname,
            area
    FROM
                    SELECT
                            t.*,
                            row_number() over(partition BY firstname order by 1) rn,
                            row_number() over(partition BY lastname order by 1) rn1
                    FROM
                            t_data t
    WHERE
            rn     = 1
    AND rn1 =1 ; 
    FIRSTNAME       LASTNAME        AREA
    bob             james           1
    cat             mud             1
    jimmy           bert            1
    sam             knight          1
    tom             sand            1
    SQL>

  • Parent-Child hierarchy based on two-column key

    Hello
    Is it possible to create a parent-child hierarchy, if the primary key of the table consists of two columns?
    My table looks like:
    TRACE_ID | DIAG_ID | SUPER_DIAG_ID
    with TRACE_ID and DIAG_ID as PK.
    If I define only DIAG_ID as PK, I can add a logical dimension (PC-hierarchy) without problems.
    However when I also add TRACE_ID to my PK, I cannot select a member key in the new logical dimension window and therefore not create a logical dimension.
    Is this a limitation of OBIEE and I have to merge the two colums (which would be rather bad, as there are FK relations to DIAG_ID) or is there a solution?
    Regards
    Matthias

    Dear Gowtham  ,
    I am very well aware of the level based hierarchy available in BO .
    The issue that i have raised is all about the Parent Child Hierarchy which creates the recursive query.
    I.e Every Parent has a child and that child can be parent of some other . (See the original example for more illustration)

  • BC4J Objects with PKs based on two columns using multiple sequences

    I have implemented a BC4J object that is based on a DB table that has two columns as the primary key. For example Table A's primary key is Group and ID and there is a DB sequence for each Group.
    I use the BC4J object using servlets and JSPs and I have been able to implement an Update form.
    I now want to implement a Create (New) form. I've read forum postings and info on the help regarding using the SequenceImpl class to override the EntityImpl object's create method as shown below:
    protected void create(AttributeList attributeList)
    super.create(attributeList);
    SequenceImpl mySeq = new SequenceImpl("MY_SEQ",getDBTransaction());
    setMyObjectId(mySeq.getSequenceNumber());
    But as you can see I need to know the value of the group attribute before I can get the next value sequence:
    For new EO belonging in Group1 I need sequence from "GROUP1_SEQ", Group 2 from "GROUP2_SEQ", etc.
    I would like to put this code in the Entity Object where it belongs. I guess my problem is simply how to create a new row in the View Object with a passed parameter which is the value of Group.
    Thanks in advance!

    Angelo:
    How is the EO suppose to receive the group id? Is it from the view row? If so, the VO can pass that group id to the EO through the attribute list and calling the
    public Row createAndInitRow(AttributeList nvp);
    API.
    Example code would be:
    ViewObject myVO;
    // myVO is initialized
    AttributeList nvp = new oracle.jbo.NameValuePairs();
    // GroupID is the attr name of the Group ID
    nvp.setAttribute("GroupID", <some-value>);
    Row row = myVO.createAndInitRow(nvp);
    If you do that the create(AttributeList attributeList) method of the EO will receive the GroupID value coming from the VO.
    Then, you can use that for your sequence.
    Thanks.
    Sung

  • Qualified list item based on two columns

    - fact table inludes following columns
    key1
    key2
    measure1
    In segment designer, update counts:
    the query must counts two columns "key1 and key2" that key1 and key2 together must be distinct.

    Here you go:
    SQL> WITH bill AS
      2  (
      3          SELECT 1000 AS billno, 101 AS advertiserid, 102 AS agencyid, 5000 AS total_value FROM DUAL UNION ALL
      4          SELECT 1001, 101, 103, 5000 FROM DUAL UNION ALL
      5          SELECT 1002, 101, 102, 1000 FROM DUAL
      6  ), account AS
      7  (
      8          SELECT 101 AS account1_id, 102 AS account2_id, 'John' AS name, 50 AS empid FROM DUAL UNION ALL
      9          SELECT 101, 103, 'James', 40 FROM DUAL UNION ALL
    10          SELECT 101, 105, 'Joe', 60 FROM DUAL
    11  )
    12  /* End Sample Data */
    13  SELECT a.name
    14       , a.empid
    15       , a.account1_id
    16       , a.account2_id
    17       , SUM(b.total_value)
    18  FROM   account a
    19  JOIN   bill    b ON  a.account1_id = b.advertiserid
    20                   AND a.account2_id = b.agencyid
    21  GROUP BY a.name
    22         , a.empid
    23         , a.account1_id
    24         , a.account2_id
    25  ;
    NAME                 EMPID          ACCOUNT1_ID          ACCOUNT2_ID   SUM(B.TOTAL_VALUE)
    John                    50                  101                  102                 6000
    James                   40                  101                  103                 5000

  • Compare two tables based on two columns

    Hi,
    my tables looks like this:
    Desc Table A (account)
    Account1_id
    Account2_id
    name,
    empid
    Table B (Bill )
    BillNo
    Advertiserid
    agencyid
    total vvalue
    I need to pick up total value from table B where the unique combination of advertiser-Agency id is the same as the given account1_id -Account2_id combination in table A for each employee id.
    In other words my output should be like
    Empid | Account_id (should be same as advertiserid)| Account2_id (same as agencyid) | sum(total_value) for this adv-agency combination.....
    objective: Get the total value from table B for each unique account1-account2 combination (advertiser-agency in other words) .
    I am not sure if I should use a coreelated subquery or how to handle the situation....Right now I am just checking the two columns separately like this:
    select.......from a,b
    where b.advertiser_id = a.account1_id and b.agencyid = b.account2id
    Is it correct to do so? I have a feeling that I am missing something if I join them seperately like this......Any advice on this?
    I am using Oracle 10g. Hope I am clear.Please let me know. Thankx in advance.

    Here you go:
    SQL> WITH bill AS
      2  (
      3          SELECT 1000 AS billno, 101 AS advertiserid, 102 AS agencyid, 5000 AS total_value FROM DUAL UNION ALL
      4          SELECT 1001, 101, 103, 5000 FROM DUAL UNION ALL
      5          SELECT 1002, 101, 102, 1000 FROM DUAL
      6  ), account AS
      7  (
      8          SELECT 101 AS account1_id, 102 AS account2_id, 'John' AS name, 50 AS empid FROM DUAL UNION ALL
      9          SELECT 101, 103, 'James', 40 FROM DUAL UNION ALL
    10          SELECT 101, 105, 'Joe', 60 FROM DUAL
    11  )
    12  /* End Sample Data */
    13  SELECT a.name
    14       , a.empid
    15       , a.account1_id
    16       , a.account2_id
    17       , SUM(b.total_value)
    18  FROM   account a
    19  JOIN   bill    b ON  a.account1_id = b.advertiserid
    20                   AND a.account2_id = b.agencyid
    21  GROUP BY a.name
    22         , a.empid
    23         , a.account1_id
    24         , a.account2_id
    25  ;
    NAME                 EMPID          ACCOUNT1_ID          ACCOUNT2_ID   SUM(B.TOTAL_VALUE)
    John                    50                  101                  102                 6000
    James                   40                  101                  103                 5000

  • HTML-DB 1.6 SQL Query (Concatenate two columns)

    Hi everyone,
    My query look like this. But I got this message
    ORA-01403: no data found
    Sql query(.....returning ... sql
    What I can do ? I want to concatenate my two columns in one.
    <pre>
    -----Résultats de la recherche
    BEGIN
    DECLARE
    requete varchar2(5000);
    v_code_type varchar2(2000);
    v_ordre varchar2(500);
    BEGIN
    :P1_NOM_BENEFICIAIRE := REPLACE(:P1_NOM_BENEFICIAIRE,' ', '%');
    :P1_NOM_BENEFICIAIRE := REPLACE(:P1_NOM_BENEFICIAIRE,'-', '%');
    requete := 'SELECT
    (FEUI.NOM_BENEFICIAIRE || ''--'' || FEUI.PRENOM_BENEFICIAIRE) ABC,
    FEUI.VALEUR_ID_BENEFICIAIRE,
    FEUI.MONTANT,
    FEUI.CODE_TYPE_DECLARATION,
    FEUI.ANNEE_FISCALE,
    FEUI.CODE_ENTITE,
    FEUI.ID_FEUILLET_IMPOT,
    FEUI.ID_AMENDEMENT,
    FEUI.NO_RELEVE_ORIGINAL_PROV,
    FEUI.ACRONYME_ID_BENEFICIAIRE,
    TYPD.SIGNIFICATION
    FROM
    S29_FEUILLET_IMPOT FEUI,
    S29_TYPE_DECLARATION TYPD
    WHERE
    (TYPD.CODE = FEUI.CODE_TYPE_DECLARATION) AND
    (ANNEE_FISCALE = :P1_ANNEE_FISCALE) AND
    (CODE_ENTITE LIKE ''%'' || SUBSTR(:P1_CODE_ENTITE,1,3) || ''%'') OR
    (CODE_ENTITE = SUBSTR(:P1_CODE_ENTITE,1,3))
    AND
    ((:P1_NAS IS NULL) OR (:P1_NAS = VALEUR_ID_BENEFICIAIRE))
    AND
    ((:P1_NEQ IS NULL) OR (:P1_NEQ = VALEUR_ID_BENEFICIAIRE))
    AND
    ((:P1_NOM_BENEFICIAIRE IS NULL) OR
    ((UPPER(NOM_BENEFICIAIRE) || UPPER(PRENOM_BENEFICIAIRE))
    LIKE ''%'' || UPPER(:P1_NOM_BENEFICIAIRE) || ''%'') OR
    ((UPPER(PRENOM_BENEFICIAIRE) || UPPER(NOM_BENEFICIAIRE))
    LIKE ''%'' || UPPER(:P1_NOM_BENEFICIAIRE) || ''%'') OR
    ((UPPER(RAISON_SOCIALE_LIGNE_1) || UPPER(RAISON_SOCIALE_LIGNE_2))
    LIKE ''%'' || UPPER(:P1_NOM_BENEFICIAIRE) || ''%'') OR
    ((UPPER(RAISON_SOCIALE_LIGNE_2) || UPPER(RAISON_SOCIALE_LIGNE_1))
    LIKE ''%'' || UPPER(:P1_NOM_BENEFICIAIRE) || ''%'') OR
    (UPPER(SUBSTR(COORDONNEE_BENEFICIAIRE_SYGBEC,1,80))
    LIKE ''%'' || UPPER(:P1_NOM_BENEFICIAIRE) || ''%'')
    IF (:P1_CODE_RELEVE = 'A') OR
    (:P1_CODE_RELEVE = 'M') OR
    (:P1_CODE_RELEVE = 'C') THEN
    v_code_type := '(
    (FEUI.CODE_TYPE_DECLARATION = ''A'') OR
    (FEUI.CODE_TYPE_DECLARATION = ''M'') OR
    (FEUI.CODE_TYPE_DECLARATION = ''C'')
    else
    v_code_type :=
    (:P1_CODE_RELEVE = CODE_TYPE_DECLARATION) OR
    (:P1_CODE_RELEVE = ''%'')
    end if;
    WWV_FLOW.DEBUG('V_CODE_TYPE EST EGALE A :' || v_code_type);
    v_ordre := 'ORDER BY NOM_BENEFICIAIRE, VALEUR_ID_BENEFICIAIRE,
    ID_FEUILLET_IMPOT, ID_AMENDEMENT';
    requete := requete || ' AND ' || v_code_type || v_ordre;
    RETURN requete;
    END;
    END;
    </pre>
    Thanks. Bye

    Thank you Scott,
    I'm sorry, I should present you a reduce sql command.
    I had construct my "long" sql command without concatenation. But, I decide to add a column just beside the other column.
    After sending my message on OTN, I tried something else, I decided to copy my sql command without concatenation in an other region. I changed my sql command in the new region by adding my new column and this ''--'' and it works very well. Sometimes, It's really difficult to understand why it doesn't.
    Thanks. Bye,

  • Update multiple rows based on two columns in same row

    I have a 1000 rows in a table I would like to update with a unique value. This unique value is a cocatenation of two columns in teh same row.
    Each row has a (i) date and a (ii) time and a (iii) date_time column. I would like to update the date_time (iii) column with a cocatenation of the (i) date and (ii) time columns.
    I know how I would update a single row but how can I update multiple rows with a cocatenation of each of the two columns - i.e put a different value into the date_time column for each row?

    this?
    update table tab_name
    set date_time =date||time
    where your_condition

  • SQL to update two columns in TABLE2 from TABLE1

    I know this is a simple question for some of you, but I am new to SQLs, so please help...
    I have two tables TABLE1 & TABLE2 as below, both tables contains more then 50million records:
    SELECT * FROM TABLE1.
    ID                        BUS_FID                WORKID                  STATIONID                 
    28400000117234         245                    13461428.25           16520877.8            
    28400000117513         403                    13461428.25           16520877.8            
    28400000117533         423                    13461428.25           16520877.8            
    28400000117578         468                    13461428.25           16520877.8            
    28400000117582         472                    13461428.25           16520877.8            
    SELECT * FROM TABLE2.
    BUS_FID                    ID                 TRPELID                RELPOS                 WORKID                 STATIONID               
    114                    28400000117658         28400000035396         23.225                                                              
    115                    28400000117659         28400000035396         23.225                                                              
    116                    28400000117660         28400000035396         23.225                                                              
    117                    28400000117661         28400000035396         23.225                                                              
    118                    28400000117662         28400000035396         23.225                                                              
    119                    28400000117663         28400000035396         23.225                                                              
    120                    28400000117664         28400000035396         23.225                                                              
    121                    28400000117665         28400000035396         23.225                                                              
    122                    28400000117666         28400000035396         23.225                                                              
    123                    28400000117667         28400000035396         23.225                                                              
    124                    28400000117668         28400000035396         23.225                                                              
    125                    28400000117669         28400000035396         23.225                                                              
    126                    28400000117670         28400000035396         23.225    Now I tried to use following SQL to update WORKID & STATIONID columns in TABLE2 but failed. BUS_FID in both tables have been UNIQUE indexed and they can be used as primary keys to join these two tables.
    UPDATE (
      SELECT  p.WORKID px,
              p.STATIONID py,
              p.BUS_FID pid,
              temp.WORKID tempx,
              temp.STATIONID tempy,
              temp.BUS_FID tempid
        FROM  TABLE1 temp,
              TABLE2 p
        WHERE pid = tempid
      SET px = tempx,
          py = tempy;
    COMMIT;with above code, Oracle returned following errors:
    SQL Error: ORA-00904: "TEMPID": invalid identifier
    00904. 00000 -  "%s: invalid identifier"Can anyone help me to correct it? Thanks~~~
    BTW, both two tables contains over 50 million records. So, if you have a better SQL to perform the same task, please let me know!
    Appreciated your help at advance.

    Hi,
    984210 wrote:
    Tried to change to
    p.bus_fid = temp.bus_fidit start running.
    Can anyone please explain to me why this is happening? Thanks!!Column aliases (such as pid and tempid in your statement) can't be used in the same query in which they are defined (except in an ORDER BY clause). Elsewhere, you have to refer to the columns by their actual names.

  • How to split rows based on two columns..

    Hi all...
    I have a requirement.
    I have product column, sell, purchace prices..(total of three columns) in a data set.
    my data set is such a way that..if sale price exists...there is no purchase price and vice versa..
    I need too present in a report ,two tables:
    table 1 consists of only Sale price items
    table 2 should contain only Pruchase Items.
    Please see the below picture for clear understanding..
    Is that doable? Where do we need to impose a condition?I tried to impose a condition but,it didnt seem to work
    http://i51.tinypic.com/29xfdc6.jpg
    Please help.

    Can you send me the template and xml file to [email protected]? I can try to help.
    Did you try to filter out the records by the sale price or purchase price column not equal to null?
    Thanks,
    Bipuser

  • Method Validator based on two columns

    Hi,
    I have a table called FndCities with attributes city_id (pk), country_id (fk) and city_name.
    I want to check if a city name is unique for a certain country. For example England can have a city name called "London", but USA might have a city called "London". However neither England not USA can have two "London" cities.
    I have implemented a custom method validator and here is the logic:
    In the FndCitiesImpl.java i created the following method:
    public boolean validateCityName(String data) {
    FndCitiesDefImpl entityDef = (FndCitiesDefImpl)getDefinitionObject();
    String originalValue = (String)getPostedAttribute(CITYNAME);
    Number originalValuePk = (Number)getPostedAttribute(COUNTRYPKFK);
    if (data != null && !data.equalsIgnoreCase(originalValue)) {
    return !(entityDef.existsByCityName(getDBTransaction(),data, originalValuePk));
    return true;
    and in the FndCitiesDefImpl.java i have implemented the method existsByCityName(DBTransaction, city_name, country_id).
    In the creation method my custom validation works fine, however when i edit a record, becuase the if statement watches for changes in the city name, when changing the Country the validation is not performed. I cannot the country id in the validateCityName method because validation is performed on one column.
    How can i achieve this?
    Thanks
    Antonis

    Hi Antonis,
    Not sure what you mean again by "JDeveloper does not handle the constraints properly." I have exactly this situation in my application (JDev 10.1.3.1), and I am using a database constraint to enforce uniqueness across 2 columns. I've customized the error messages (see Re: Unique key existence check and ER: ADF BC - allow custom error msgs for common exceptions (e.g. DML) ). Works just dandy.
    John

  • Numbering lines based on two columns

    Hi Everyone,
    I´d like to know if there is a way to achieve the numbering presented on the second table below with only native Oracle functions, like ROW_COUNT() over partition, etc.
    I´m using Oracle 10g.
    The logic used is:
    Starting from 1, increment one every time the ORIGIN is the same as the FIRST ORIGIN of the group of rows (ID).
    ID    ORIGIN    DESTINATION    ORDER
    1     A         B              1
    1     B         A              2
    1     A         B              3
    1     B         C              4
    1     C         A              5
    ID     ORIGIN    DESTINATION    ORDER    NUMBERING
    1      A         B              1        1
    1      B         A              2        1
    1      A         B              3        2
    1      B         C              4        2
    1      C         A              5        2In order to compare the ORIGIN of each row with the FIRST ORIGIN of the group I used the LAG function to create a column that will have the FIRST ORIGIN of the group value.
    However I was not able to number the lines as shown above (column NUMBERING).
    Any help will be much appreciated.
    Test query:
    WITH T AS
      SELECT 1 ID, 'A' ORIGIN, 'B' DESTINATION, 1 ORDERING FROM DUAL UNION ALL
      SELECT 1 ID, 'B' ORIGIN, 'A' DESTINATION, 2 ORDERING FROM DUAL UNION ALL
      SELECT 1 ID, 'A' ORIGIN, 'B' DESTINATION, 3 ORDERING FROM DUAL UNION ALL
      SELECT 1 ID, 'B' ORIGIN, 'C' DESTINATION, 4 ORDERING FROM DUAL UNION ALL
      SELECT 1 ID, 'C' ORIGIN, 'A' DESTINATION, 5 ORDERING FROM DUAL
      SELECT T.ID
           , T.ORIGIN
           , T.DESTINATION
           , T.ORDERING
           , LAG (T.ORIGIN, T.ORDERING -1, 0) OVER (PARTITION BY T.ID
                                                        ORDER BY T.ID
                                                               , T.ORDERING) FIRST_ORIGIN_OF_GROUP
        FROM T
    ORDER BY T.ID
           , T.ORDERING

    Hi,
    Here's one way:
    WITH     got_first_origin     AS
         SELECT     id, origin, destination, ordering
         ,     FIRST_VALUE (origin) OVER ( PARTITION BY  id
                                          ORDER BY         ordering
                                     ) AS first_origin
         FROM    t
    SELECT     id, origin, destination, ordering
    ,     COUNT ( CASE
                        WHEN  origin = first_origin
                  THEN  1
                    END
               )     OVER ( PARTITION BY  id
                           ORDER BY      ordering
                   ) AS numbering
    FROM     got_first_origin
    ;This assumes that the combination of id and ordering is unique. Within an id, ordering does not have to be consecutive integers, or anything like that.
    Analytic functions can't be nested (the argument to the anlytic COUNT function can't call the analytic FIRST_VALUE function); that's why the sub-query is necessary.
    You could do something with LAG, like you tried, rather than FIRST_VALUE, but you'd still need a sub-query, for the same reason.

  • How to display data based on two columns in Apex calendar?

    I have a table for holiday details with 2 date columns...from-date and a to-date. I need to display the name of the person for the date range they have specified. For Ex if i applied for leaves from may 1 to may 4...the calendar should display my name for 4 dates i.e may1,2,3 and 4
    I am new user in apex and still trying new things. Please help me achieve this.

    Swetha
    I created an application using Apex. It is a calendar application to show events that are happening. I ran into an issue with it
    If there is an event that occurs during an interval like August15 - August22, the event is shown only on August15, which is the first day of the event. I would like to show it in all days from August15-22.
    Here are the items coming from the page
    event_id number,
    employee_id number
    date_from date,
    date_to date,
    due_date date,
    act_id number,
    act_loc varchar2,
    reminder varchar2,
    frequency varchar2,
    division varchar2,
    event_status varchar2
    I am looking to write a process / procedure where it can show the same event on all the days it is occurring
    Thanks in advance
    Latha

Maybe you are looking for