SQL Help getting Max() date....

Hi gurus, Here is my situation:
Here is the sample data:
Policy_Id Policy-Exp_Dt COl_1
123_____10/30/2008 __ 333
123_____ 09/25/2008___445
123_____ 08/30/2008___443
Here i have to get the Policy-Exp_Dt from the second row; In other words for all rows which have a similar Policy_Id i should first find out the max(Policy-Exp_Dt) and get the next smallest available date to that.
I have tried using
select Policy_Id, COl_1, Policy_Exp_Dt from
table_1
where Policy-Exp_Dt = (select max(Policy-Exp_Dt)-1 from
table_1 a
where a.policy_id = table_1.policy_id)
but here i am getting the value = 10/30/2008 - 1 which is 10/29/2008 but i need the value 9/25/2008 which is the next available date less than the max() date.
Please Advise.
Edited by: user521009 on Jan 9, 2009 1:56 PM

I thought to use lag - maybe not as appropriate a ranking functions.
Also we have a case where there is only One record for a policy - exclude this I guess!
drop table Max_but_One;
create table Max_but_One
  Policy_Id      integer      not null,
  Policy_Expires date         not null,
  Policy_Note    varchar2(20) not null
-- Standard data
insert into Max_but_One values (123, to_date('30-08-2008','dd-mm-yyyy'), 'First note');
insert into Max_but_One values (123, to_date('25-09-2008','dd-mm-yyyy'), 'Second note');
insert into Max_but_One values (123, to_date('30-10-2008','dd-mm-yyyy'), 'Third note');
-- Standard data again for double check
insert into Max_but_One values (223, to_date('01-11-2008','dd-mm-yyyy'), 'First note');
insert into Max_but_One values (223, to_date('02-11-2008','dd-mm-yyyy'), 'Second note');
-- Only one record for a policy!
insert into Max_but_One values (323, to_date('01-12-2008','dd-mm-yyyy'), 'First note');
-- Two or more records for a policy both having the same date which is prior to the max
insert into Max_but_One values (423, to_date('10-12-2008','dd-mm-yyyy'), 'First note');
insert into Max_but_One values (423, to_date('10-12-2008','dd-mm-yyyy'), 'Second note');
insert into Max_but_One values (423, to_date('11-12-2008','dd-mm-yyyy'), 'Third note');
break on Policy_ID
select Policy_Id, Policy_Expires, Policy_Note
  from Max_but_One
order by Policy_Id, Policy_Expires
POLICY_ID POLICY_EX POLICY_NOTE
       123 30-AUG-08 First note
           25-SEP-08 Second note
           30-OCT-08 Third note
       223 01-NOV-08 First note
           02-NOV-08 Second note
       323 01-DEC-08 First note
       423 10-DEC-08 First note
           10-DEC-08 Second note
           11-DEC-08 Third note
-- Max Policy_Expires
select t.*
  from (select Policy_Id, Policy_Expires, Policy_Note
              ,max(Policy_Expires) over (partition by Policy_Id) as Max_Policy_Expires
          from Max_but_One
       ) t
where t.Policy_Expires = t.Max_Policy_Expires
POLICY_ID POLICY_EX POLICY_NOTE          MAX_POLIC
       123 30-OCT-08 Third note           30-OCT-08
       223 02-NOV-08 Second note          02-NOV-08
       323 01-DEC-08 First note           01-DEC-08
       423 11-DEC-08 Third note           11-DEC-08
-- Using LAG
select t.Policy_Id
      ,t.Prior_Policy_Expires as Policy_Expires
      ,t.Prior_Policy_Note    as Policy_Note
  from (select Policy_Id, Policy_Expires, Policy_Note
              ,max(Policy_Expires) over (partition by Policy_Id) as Max_Policy_Expires
            ,lag(Policy_Expires) over (partition by Policy_Id order by Policy_Expires) as Prior_Policy_Expires
              ,lag(Policy_Note)    over (partition by Policy_Id order by Policy_Expires) as Prior_Policy_Note
          from Max_but_One
       ) t
where t.Policy_Expires = t.Max_Policy_Expires
POLICY_ID POLICY_EX POLICY_NOTE
       123 25-SEP-08 Second note
       223 01-NOV-08 First note
       323
       423 10-DEC-08 Second note
-- To exclude the single record policy then add and t.Prior_Policy_Expires is not null
select t.Policy_Id
      ,t.Prior_Policy_Expires as Policy_Expires
      ,t.Prior_Policy_Note    as Policy_Note
  from (select Policy_Id, Policy_Expires, Policy_Note
              ,max(Policy_Expires) over (partition by Policy_Id) as Max_Policy_Expires
            ,lag(Policy_Expires) over (partition by Policy_Id order by Policy_Expires) as Prior_Policy_Expires
              ,lag(Policy_Note)    over (partition by Policy_Id order by Policy_Expires) as Prior_Policy_Note
          from Max_but_One
       ) t
where t.Policy_Expires = t.Max_Policy_Expires
   and t.Prior_Policy_Expires is not null
POLICY_ID POLICY_EX POLICY_NOTE
       123 25-SEP-08 Second note
       223 01-NOV-08 First note
       423 10-DEC-08 Second note
-- 423 is randomly picked here - could equally have got {423, 10-DEC-08, First note}

Similar Messages

  • In mdx how to get max date for all employees is it posible shall we use group by in mdx

    in mdx how to get max date for all employees is it posible shall we use group by in mdx
    example
    empno  ename date
    1         hari        12-01-1982
    1         hari        13-06-2000
    by using above data i want to get max data

    Hi Hari3109,
    According to your description, you want to get the max date for the employees, right?
    In your scenario, do you want to get the max date for all the employees or for each employee? In MDX, we have the Max function to achieve your requirement. You can refer to Naveen's link or the link below to see the details.
    http://www.sqldbpros.com/2013/08/get-the-max-date-from-a-cube-using-mdx/
    If this is not what you want, please provide us more information about the structure of you cube, so that we can make further analysis.
    Regards,
    Charlie Liao
    TechNet Community Support

  • OPEN SQL - use of subquery to get max date

    Hello,
    I am trying to use a subquery to get the latest record, but cannot get the syntax correct.
    select single from hrp1001 into mydata
    where objid = '122334'
    where begda  = ( select max ( begda ) from hrp1001 where objid  = '122334' )
    but cannot get it right.
    I am just trying to get the record with the max(date).
    Thanks

    Hello,
    To get a better performance, I suggest you the following:
    select single * from hrp1001 into corresponding fields of mydata
    where objid = '122334'
    order by begda descending.
    Regards,

  • How to get max date in variable using  dynamic query

    Hi,
    the following code gets all dates from sourcetable i want only max date , so i thought max function can be added and it will work
    but still i have to create a table for one value(scalar) can get it in any other effeciant way.
    declare
    TYPE date_string IS TABLE OF VARCHAR(1000);
    date_obj date_string;
    BEGIN
    EXECUTE IMMEDIATE 'SELECT to_char('''||day1||'-'||month1||'-'||year1||''') FROM '||source_schema||'.'|| sourcetable ||'' bulk collect INTO date_obj;
    FOR indx IN date_obj.FIRST..date_obj.LAST loop
    dbms_output.put_line(
    date_obj(indx));
    END loop;
    DBMS_OUTPUT.PUT_LINE('Sample output');
    END;
    yours sincerely

    944768 wrote:
    the following code gets all dates from sourcetableNo it doesn't. What is the datatype of day1, month1 and year1? They cannot be DATE datatypes otherwise your TO_CHAR would fail with all that concatenation going on. And your TO_CHAR is returning a VARCHAR2 datatype... so you cannot say that it is getting all dates... because there are no DATE datatypes returned. It's getting a lot of strings, but certainly not DATE's.
    i want only max date , so i thought max function can be added and it will work You can use the MAX function on a DATE datatype, but not on strings (at least not in the way you intend it to work).
    Converting it to a DATE before doing the MAX will allow you to get the maximum date (assuming the date format is correct)
    EXECUTE IMMEDIATE 'SELECT max(to_date(to_char('''||day1||'-'||month1||'-'||year1||'''),''DD-MM-YYYY'')) FROM  '||source_schema||'.'|| sourcetable ||'' bulk collect INTO date_obj;Then you will find have the other issues...
    a) you are then going to be fetching your DATEs in to a collection of VARCHAR strings. (Not even VARCHAR2, very poor). This should be DATE datatype
    b) you are bulk collecting into a collection, when you are using MAX which will return a single value in your example
    And you really should address the design issues:
    c) why are day, month and year, not being stored in the database as a single DATE datatype in the first place
    d) why does your code not know the name of the table it's querying requiring the use of very poor dynamic SQL techniques.
    e) why are you loading data in a collection in expensive PGA memory... what can't you do in SQL that requires you to collect the data into memory first?

  • Teststand SQL reuest get MAX of a Column

    Spoiler (Highlight to read)
    Hello,
    In Teststand 3.1, I try to get the MAX of a column called  Col1 in the table myTAB.
    To do that; I have writen in the Open Statement the following request
    SELECT MAX(myTAB.Col1) FROM myTAB" Thanks. Correct execution in teststand
    Question : How do I get the result with the SQL Action Step
    Thank you by advance for your help
    Solved!
    Go to Solution.

    Hello Rodéric,
    Thank you very much for the answer.
    I tried your suggestion as it is but unfortunatelly Teststand gives back an error because it can't manage correctly the locals.max in the request.
    However I tried other may your idea of using the key word "as" :
    First I use :
    Open Statement : SELECT MAX(myTAB.Col1) as MAXI FROM myTAB
    I don't know how teststand manage the "variable" MAXI.
    But when I secondly add the step
    SQL Action : Get - Retrive Values from record with as Column/Parameter Values:
    Name/Number : "MAXI"
    Values : Locals.Max
    It works correctly
    Thank you a lot
    Ham

  • Need help getting mysql data

    I have two pages, page X has all the record and page Y has a record that is based  on a url paramater sent from page X, meaning at the end in the browser I have something like this:
    the_site/item_detail.php?item_name=KEDS, CHUKKA, BLUE SLATE
    The thing is, I want to get another record on page Y where I want to have some of the information of the first record which receives its URL paramater from page X.
    More clear maybe:
    On page Y, I have one record which receives its data info from a URL paramater sent from page X
    on thi same page, I want to create another record and I would like this new record to use a column from the first one to get its data result.
    Thank

    I am retrieving data
    on page Y there already a recordset that retrievs data based on the URL parameter sent from page X (recordset 1)
    On the same page, I want to create another recordset (retrieve more data) and to retrieve this data (of recordset 2 on the same oage) I want to be able to use some information from recordset 1.
    I hope your understand what I mean

  • How to get max(date) with BI Answers?

    Hi,
    I have a fact table with costs of projects and several dimension tables. The data in the fact table is stored day-based and is related to a time dimension. Additionally there is a relation between the fact table and the project dimension. A project has several dimension attributes like "current"
    Now I want to create the following query in BI Answers:
    Get the costs to a project where the "current" attribute was set to Y and show the related date.
    My thoughts were, that I'm looking in the project dimension where the "current" attribute is set to Y and do a join on the fact table. Therefore I get several dates, because there are more than one day where the project status was set to Y. How can I get the last, highest date?
    Greetings

    Hi,
    Maybe you could order by date descending and show the Top N (=1).
    Good Luck,
    Daan Bakboord

  • Trying to get max date grouped by type

    hello,
    i have a request table with:
    request name
    request start date
    The requests run daily so i have multiple records. In answers i want to display request name and the max(request start date), grouped by request name. Is it possible to due this in answers only? if i must use the repository how do i do it? I'm new to building subject areas.

    You can do this in answers only, If you dont have access to RPD.
    Sol1: Create a report with two columns request name,request start date. Open pivot table and add request start date to measures and apply Aggregation of Max on date.
    sol2: Create a report with two columns request name,request start date, Change the Fx of request start date to max(request start date by request name) . This way table view also show request max date by request names.

  • Help - Need to Get Max(Date) from An Unrelated Table in PowerPivot

    I have two tables in my Power Pivot model:
    Table A (a many table)
    Asset    
    SerialNumber                   
    User
    CTUT111                             
    YC112233                                            
    Bob
    CTUT222                             
    ZZ221144                                            
    Susy
    CTUT222                             
    ZZ221144                                            
    Larry
    CTUT333                             
    AB332244                                           
    Bob
    Table B (a many table, a CSV import from another system)
    Asset                    
    SerialNumber                                   
    CheckIn_Date
    CTUT111                             
    YC112233                                            
    6/15/2014
    CTUT111                             
    YC112233                                            
    6/20/2014
    CTUT222                             
    ZZ221144                                            
    6/18/2014
    CTUT333                             
    AB332244                                           
    6/20/2014
    I know it appears odd that Table B would have two entries for the same Asset (CTUT111), but it does.
    I know I could write a SQL query that gave me the MAX(CheckIn_Date), but I’m not staging these datasets in a SQL server first. 
    I’m pulling directly from CSV tables.
    I don’t want to have bridge tables either, if possible. 
    So, I’m left with a many-to-many situation in Power Pivot.
    I want to add a Calculated Column to Table A, called ‘Latest CheckIn Date’ – which I get from Table B, matching on Serial Number.
    So, when I’m done, I would expect the value for Asset=CTUT111 to be 6/20/2014 (since it’s the MAX of a value of dates)
    I’m trying this pattern from Marco Russo in which you don’t need to relate two tables to exchange information, but it doesn’t appear to be working.
    =CALCULATE (
    MAX ( VALUES ( TableB[CheckIn_Date] ) ),
    FILTER (
    TableB,
    'TableA'[SerialNumber]
    = TableB[SerialNumber]
    I’ve also tried to use LOOKUPVALUE, but I can’t seem to figure it out.
    Would appreciate the help.
    Thanks in advance.
    -Eric

    Hi Eric,
    Please, try this one formula:
    =CALCULATE (
                MAXX ( VALUES( TableB[CheckIn_Date] ); TableB[CheckIn_Date] );
                FILTER (
                    TableB;
                    'TableA'[SerialNumber] = TableB[SerialNumber]
    P.S. In my locale I use ";". According to your locale you should use ",".
    Truly yours,
    Paul

  • Help to get max date of the group

    Hi, How I can get the max(date1) for the group on the basis of Code1,Code2,Code3.
    Code1    Code2   Code3     Date1         RTCODE
    A           A1        A2         1/1/2012     SER
    A           A1        A2         1/1/2013     SER
    A           A1        A2         1/1/2015     TER
    B          B1        B2         1/1/2011       JTS
    B          B1        B2         1/1/2012      JTR
    C          C1       C2         1/1/2010      HYR
    C          C1       C2         1/1/2011       JST
    Expected results from query should be:
    Code1    Code2   Code3     Date1         RTCODE
    A           A1        A2         1/1/2015      TER
    B           B1        B2         1/1/2012      JTR
    C          C1       C2          1/1/2011       JST

    Hi,
    You can try this:
    CREATE TABLE #T
    CODE1 VARCHAR(5),
    CODE2 VARCHAR(5),
    CODE3 VARCHAR(5),
    DATE1 DATE,
    RTCODE VARCHAR(5)
    --DROP TABLE #T
    INSERT INTO #T
    VALUES
    ('A','A1','A2','20120101','SER'),
    ('A','A1','A2','20130101','SER'),
    ('A','A1','A2','20150101','TER'),
    ('B','B1','B2','20110101','JTS'),
    ('B','B1','B2','20120101','JTR'),
    ('C','C1','C2','20100101','HYR'),
    ('C','C1','C2','20110101','JST');
    --TRUNCATE TABLE #T
    WITH TEST AS
    SELECT CODE1, CODE2, CODE3, MAX(DATE1) AS DT_MAX
    FROM #T
    GROUP BY CODE1, CODE2, CODE3
    SELECT T.CODE1,T.CODE2, T.CODE3, T.DT_MAX,#T.RTCODE
    FROM TEST AS T
    INNER JOIN #T ON T.CODE1=#T.CODE1
    AND T.CODE2=#T.CODE2
    AND T.CODE3=#T.CODE3
    AND T.DT_MAX=#T.DATE1
    ORDER BY T.CODE1,T.CODE2,T.CODE3
    Regards,
    Reshma
    Please Vote as Helpful if an answer is helpful and/or Please mark Proposed as Answer or Mark As Answer when question is answered

  • Getting max date and max time column plz help

    hi
    i have a table with suppose 7 columns with date and time column seperate
    i want to design a query which retrieve the current or the maxmum date with the max of time in that date.
    columns a ,b,c, date, time
    22-05-07 20
    23-05-07 50
    24-05-07 40
    25-05-07 30
    22-05-07 20
    ans " suppose current date is 25 "
    a,b,c,25-05-07,40

    try like this..
    SQL> with rt as
      2  (select 1 col1,'22-05-07' dt, 20 tm from dual union all
      3  select 2,'23-05-07', 50 from dual union all
      4  select 3,'24-05-07', 40 from dual union all
      5  select 4,'25-05-07', 30 from dual union all
      6  select 5,'25-05-07', 45 from dual union all
      7  select 6,'22-05-07', 20 from dual)
      8  select col1,dt,tm from
      9  (select col1,
    10      dt,
    11      max(tm) over(partition by to_date(dt,'DD-MM-RR') order by col1 desc) tm,
    12      row_number() over(partition by to_date(dt,'DD-MM-RR') order by col1 desc) rn
    13  from rt where to_date(dt,'DD-MM-RR') in (select max(to_date(dt,'DD-MM-RR')) dt from rt))
    14  where rn = 1;
          COL1 DT               TM
             5 25-05-07         45
    SQL>

  • Connect by - sql help : getting error ORA-01489: result of string concatena

    here is an sql query and I am trying to cook a decode but since there are many columns invloved when I am trying to run this I am getting the following error:
    ORA-01489: result of string concatenation is too long
    Any kind of help is appreciated, I need to get this going otherwise I am dead :(
    Regards
    Rahul
    SQL:
    select sys_connect_by_path(c.decode_prep,'-') decode_prep
    from (select 'DECODE(BIAPPS_11.'||substr(b.all_cols,instr(b.all_cols,',',1,a.rn)+1,instr(b.all_cols,',',1,a.rn+1)-instr(b.all_cols,',',1,a.rn)-1)||','||'RAHULKALRA.'||substr(b.all_cols,instr(b.all_cols,',',1,a.rn)+1,instr(b.all_cols,',',1,a.rn+1)-instr(b.all_cols,',',1,a.rn)-1)||',''1'',''0'')' decode_prep, rownum curr, rownum -1 prev
    from (select rownum rn
    from dual connect by rownum <=
    (select (length('ROW_WID,COST_CENTER_NUM,COST_CENTER_NAME,COST_CENTER_DESC,CONTROL_AREA_NUM,CONTROL_AREA_NAME,CATEGORY_CODE,CATEGORY_NAME,CATEGORY_DESC,MANAGER_NAME,CURRENCY_CODE,CURRENCY_NAME,LANGUAGE_CODE,LANGUAGE_NAME,ST_ADDRESS1,ST_ADDRESS2,POST_OFFICE_BOX,CITY_NAME,STATE_CODE,STATE_NAME,REGION_CODE,REGION_NAME,COUNTRY_CODE,COUNTRY_NAME,POSTAL_CODE,PHONE_NUM,FAX_NUM,CSCN_HIER1_CODE,CSCN_HIER1_NAME,CSCN_HIER2_CODE,CSCN_HIER2_NAME,CSCN_HIER3_CODE,CSCN_HIER3_NAME,CSCN_HIER4_CODE,CSCN_HIER4_NAME,CSCN_HIER5_CODE,CSCN_HIER5_NAME,CSCN_HIER6_CODE,CSCN_HIER6_NAME,ACTIVE_FLG,CREATED_BY_WID,CHANGED_BY_WID,CREATED_ON_DT,CHANGED_ON_DT,AUX1_CHANGED_ON_DT,AUX2_CHANGED_ON_DT,AUX3_CHANGED_ON_DT,AUX4_CHANGED_ON_DT,SRC_EFF_FROM_DT,SRC_EFF_TO_DT,EFFECTIVE_FROM_DT,EFFECTIVE_TO_DT,DELETE_FLG,CURRENT_FLG,W_INSERT_DT,W_UPDATE_DT,DATASOURCE_NUM_ID,ETL_PROC_WID,INTEGRATION_ID,SET_ID,TENANT_ID,X_CUSTOM')
    - length(replace('ROW_WID,COST_CENTER_NUM,COST_CENTER_NAME,COST_CENTER_DESC,CONTROL_AREA_NUM,CONTROL_AREA_NAME,CATEGORY_CODE,CATEGORY_NAME,CATEGORY_DESC,MANAGER_NAME,CURRENCY_CODE,CURRENCY_NAME,LANGUAGE_CODE,LANGUAGE_NAME,ST_ADDRESS1,ST_ADDRESS2,POST_OFFICE_BOX,CITY_NAME,STATE_CODE,STATE_NAME,REGION_CODE,REGION_NAME,COUNTRY_CODE,COUNTRY_NAME,POSTAL_CODE,PHONE_NUM,FAX_NUM,CSCN_HIER1_CODE,CSCN_HIER1_NAME,CSCN_HIER2_CODE,CSCN_HIER2_NAME,CSCN_HIER3_CODE,CSCN_HIER3_NAME,CSCN_HIER4_CODE,CSCN_HIER4_NAME,CSCN_HIER5_CODE,CSCN_HIER5_NAME,CSCN_HIER6_CODE,CSCN_HIER6_NAME,ACTIVE_FLG,CREATED_BY_WID,CHANGED_BY_WID,CREATED_ON_DT,CHANGED_ON_DT,AUX1_CHANGED_ON_DT,AUX2_CHANGED_ON_DT,AUX3_CHANGED_ON_DT,AUX4_CHANGED_ON_DT,SRC_EFF_FROM_DT,SRC_EFF_TO_DT,EFFECTIVE_FROM_DT,EFFECTIVE_TO_DT,DELETE_FLG,CURRENT_FLG,W_INSERT_DT,W_UPDATE_DT,DATASOURCE_NUM_ID,ETL_PROC_WID,INTEGRATION_ID,SET_ID,TENANT_ID,X_CUSTOM',',')))+1 total_cols
    from dual)) a, (select ','||'ROW_WID,COST_CENTER_NUM,COST_CENTER_NAME,COST_CENTER_DESC,CONTROL_AREA_NUM,CONTROL_AREA_NAME,CATEGORY_CODE,CATEGORY_NAME,CATEGORY_DESC,MANAGER_NAME,CURRENCY_CODE,CURRENCY_NAME,LANGUAGE_CODE,LANGUAGE_NAME,ST_ADDRESS1,ST_ADDRESS2,POST_OFFICE_BOX,CITY_NAME,STATE_CODE,STATE_NAME,REGION_CODE,REGION_NAME,COUNTRY_CODE,COUNTRY_NAME,POSTAL_CODE,PHONE_NUM,FAX_NUM,CSCN_HIER1_CODE,CSCN_HIER1_NAME,CSCN_HIER2_CODE,CSCN_HIER2_NAME,CSCN_HIER3_CODE,CSCN_HIER3_NAME,CSCN_HIER4_CODE,CSCN_HIER4_NAME,CSCN_HIER5_CODE,CSCN_HIER5_NAME,CSCN_HIER6_CODE,CSCN_HIER6_NAME,ACTIVE_FLG,CREATED_BY_WID,CHANGED_BY_WID,CREATED_ON_DT,CHANGED_ON_DT,AUX1_CHANGED_ON_DT,AUX2_CHANGED_ON_DT,AUX3_CHANGED_ON_DT,AUX4_CHANGED_ON_DT,SRC_EFF_FROM_DT,SRC_EFF_TO_DT,EFFECTIVE_FROM_DT,EFFECTIVE_TO_DT,DELETE_FLG,CURRENT_FLG,W_INSERT_DT,W_UPDATE_DT,DATASOURCE_NUM_ID,ETL_PROC_WID,INTEGRATION_ID,SET_ID,TENANT_ID,X_CUSTOM'||',' all_cols from dual) b) c
    start with curr = 1
    connect by prior curr = prev
    order by length(sys_connect_by_path(c.decode_prep,'-')) desc
    same as above sql only difference is here I am pulling the first record from the result set which above query returns :
    select ltrim(replace(decode_prep,'-','||'),'||') decode_prep
    from (select sys_connect_by_path(c.decode_prep,'-') decode_prep
    from (select 'DECODE(BIAPPS_11.'||substr(b.all_cols,instr(b.all_cols,',',1,a.rn)+1,instr(b.all_cols,',',1,a.rn+1)-instr(b.all_cols,',',1,a.rn)-1)||','||'RAHULKALRA.'||substr(b.all_cols,instr(b.all_cols,',',1,a.rn)+1,instr(b.all_cols,',',1,a.rn+1)-instr(b.all_cols,',',1,a.rn)-1)||',''1'',''0'')' decode_prep, rownum curr, rownum -1 prev
    from (select rownum rn
    from dual connect by rownum <=
    (select (length('ROW_WID,COST_CENTER_NUM,COST_CENTER_NAME,COST_CENTER_DESC,CONTROL_AREA_NUM,CONTROL_AREA_NAME,CATEGORY_CODE,CATEGORY_NAME,CATEGORY_DESC,MANAGER_NAME,CURRENCY_CODE,CURRENCY_NAME,LANGUAGE_CODE,LANGUAGE_NAME,ST_ADDRESS1,ST_ADDRESS2,POST_OFFICE_BOX,CITY_NAME,STATE_CODE,STATE_NAME,REGION_CODE,REGION_NAME,COUNTRY_CODE,COUNTRY_NAME,POSTAL_CODE,PHONE_NUM,FAX_NUM,CSCN_HIER1_CODE,CSCN_HIER1_NAME,CSCN_HIER2_CODE,CSCN_HIER2_NAME,CSCN_HIER3_CODE,CSCN_HIER3_NAME,CSCN_HIER4_CODE,CSCN_HIER4_NAME,CSCN_HIER5_CODE,CSCN_HIER5_NAME,CSCN_HIER6_CODE,CSCN_HIER6_NAME,ACTIVE_FLG,CREATED_BY_WID,CHANGED_BY_WID,CREATED_ON_DT,CHANGED_ON_DT,AUX1_CHANGED_ON_DT,AUX2_CHANGED_ON_DT,AUX3_CHANGED_ON_DT,AUX4_CHANGED_ON_DT,SRC_EFF_FROM_DT,SRC_EFF_TO_DT,EFFECTIVE_FROM_DT,EFFECTIVE_TO_DT,DELETE_FLG,CURRENT_FLG,W_INSERT_DT,W_UPDATE_DT,DATASOURCE_NUM_ID,ETL_PROC_WID,INTEGRATION_ID,SET_ID,TENANT_ID,X_CUSTOM')
    - length(replace('ROW_WID,COST_CENTER_NUM,COST_CENTER_NAME,COST_CENTER_DESC,CONTROL_AREA_NUM,CONTROL_AREA_NAME,CATEGORY_CODE,CATEGORY_NAME,CATEGORY_DESC,MANAGER_NAME,CURRENCY_CODE,CURRENCY_NAME,LANGUAGE_CODE,LANGUAGE_NAME,ST_ADDRESS1,ST_ADDRESS2,POST_OFFICE_BOX,CITY_NAME,STATE_CODE,STATE_NAME,REGION_CODE,REGION_NAME,COUNTRY_CODE,COUNTRY_NAME,POSTAL_CODE,PHONE_NUM,FAX_NUM,CSCN_HIER1_CODE,CSCN_HIER1_NAME,CSCN_HIER2_CODE,CSCN_HIER2_NAME,CSCN_HIER3_CODE,CSCN_HIER3_NAME,CSCN_HIER4_CODE,CSCN_HIER4_NAME,CSCN_HIER5_CODE,CSCN_HIER5_NAME,CSCN_HIER6_CODE,CSCN_HIER6_NAME,ACTIVE_FLG,CREATED_BY_WID,CHANGED_BY_WID,CREATED_ON_DT,CHANGED_ON_DT,AUX1_CHANGED_ON_DT,AUX2_CHANGED_ON_DT,AUX3_CHANGED_ON_DT,AUX4_CHANGED_ON_DT,SRC_EFF_FROM_DT,SRC_EFF_TO_DT,EFFECTIVE_FROM_DT,EFFECTIVE_TO_DT,DELETE_FLG,CURRENT_FLG,W_INSERT_DT,W_UPDATE_DT,DATASOURCE_NUM_ID,ETL_PROC_WID,INTEGRATION_ID,SET_ID,TENANT_ID,X_CUSTOM',',')))+1 total_cols
    from dual)) a, (select ','||'ROW_WID,COST_CENTER_NUM,COST_CENTER_NAME,COST_CENTER_DESC,CONTROL_AREA_NUM,CONTROL_AREA_NAME,CATEGORY_CODE,CATEGORY_NAME,CATEGORY_DESC,MANAGER_NAME,CURRENCY_CODE,CURRENCY_NAME,LANGUAGE_CODE,LANGUAGE_NAME,ST_ADDRESS1,ST_ADDRESS2,POST_OFFICE_BOX,CITY_NAME,STATE_CODE,STATE_NAME,REGION_CODE,REGION_NAME,COUNTRY_CODE,COUNTRY_NAME,POSTAL_CODE,PHONE_NUM,FAX_NUM,CSCN_HIER1_CODE,CSCN_HIER1_NAME,CSCN_HIER2_CODE,CSCN_HIER2_NAME,CSCN_HIER3_CODE,CSCN_HIER3_NAME,CSCN_HIER4_CODE,CSCN_HIER4_NAME,CSCN_HIER5_CODE,CSCN_HIER5_NAME,CSCN_HIER6_CODE,CSCN_HIER6_NAME,ACTIVE_FLG,CREATED_BY_WID,CHANGED_BY_WID,CREATED_ON_DT,CHANGED_ON_DT,AUX1_CHANGED_ON_DT,AUX2_CHANGED_ON_DT,AUX3_CHANGED_ON_DT,AUX4_CHANGED_ON_DT,SRC_EFF_FROM_DT,SRC_EFF_TO_DT,EFFECTIVE_FROM_DT,EFFECTIVE_TO_DT,DELETE_FLG,CURRENT_FLG,W_INSERT_DT,W_UPDATE_DT,DATASOURCE_NUM_ID,ETL_PROC_WID,INTEGRATION_ID,SET_ID,TENANT_ID,X_CUSTOM'||',' all_cols from dual) b) c
    start with curr = 1
    connect by prior curr = prev
    order by length(sys_connect_by_path(c.decode_prep,'-')) desc)
    where rownum = 1
    Edited by: Mac_Freak_Rahul on Nov 28, 2012 1:31 AM : in the first sql ')'
    removed after desc in the last line so now this query will run and throw an error.

    Clearly your error is because the string concatenation you are doing with sys_connect_by_path is exceeding the 4000 bytes permitted by SQL.
    In that case you need to concatenate your data into a CLOB datatype, for which you'll need a CLOB aggregation function...
    create or replace type clobagg_type as object
      text clob,
      static function ODCIAggregateInitialize(sctx in out clobagg_type) return number,
      member function ODCIAggregateIterate(self in out clobagg_type, value in clob) return number,
      member function ODCIAggregateTerminate(self in clobagg_type, returnvalue out clob, flags in number) return number,
      member function ODCIAggregateMerge(self in out clobagg_type, ctx2 in clobagg_type) return number
    create or replace type body clobagg_type is
      static function ODCIAggregateInitialize(sctx in out clobagg_type) return number is
      begin
        sctx := clobagg_type(null) ;
        return ODCIConst.Success ;
      end;
      member function ODCIAggregateIterate(self in out clobagg_type, value in clob) return number is
      begin
        self.text := self.text || value ;
        return ODCIConst.Success;
      end;
      member function ODCIAggregateTerminate(self in clobagg_type, returnvalue out clob, flags in number) return number is
      begin
        returnValue := self.text;
        return ODCIConst.Success;
      end;
      member function ODCIAggregateMerge(self in out clobagg_type, ctx2 in clobagg_type) return number is
      begin
        self.text := self.text || ctx2.text;
        return ODCIConst.Success;
      end;
    end;
    create or replace function clobagg(input clob) return clob
      deterministic
      parallel_enable
      aggregate using clobagg_type;
    SQL> select trim(',' from clobagg(ename||',')) as enames from emp;
    ENAMES
    SMITH,ALLEN,WARD,JONES,MARTIN,BLAKE,CLARK,SCOTT,KING,TURNER,ADAMS,JAMES,FORD,MILLER
    SQL> ed
    Wrote file afiedt.buf
      1  with t as
      2    (select 'PFL' c1, 0 c2,110 c3 from dual union all
      3     select 'LHL', 0 ,111 from dual union all
      4     select 'PHL', 1, 111 from dual union all
      5     select 'CHL', 2, 111 from dual union all
      6     select 'DHL', 0, 112 from dual union all
      7     select 'VHL', 1, 112 from dual union all
      8     select 'CPHL', 0, 114 from dual union all
      9     select 'WDCL', 1, 114 from dual union all
    10     select 'AHL' ,2 ,114 from dual union all
    11     select 'NFDL', 3, 114 from dual)
    12  --
    13  -- end of test data
    14  --
    15  select trim(clobagg(c1||' ')) as c1, c3
    16  from (select * from t order by c3, c2)
    17  group by c3
    18* order by c3
    SQL> /
    C1                                     C3
    PFL                                   110
    LHL CHL PHL                           111
    DHL VHL                               112
    CPHL AHL NFDL WDCL                    114

  • Need SQL help in select data from 2 table..

    hi,
    i need some help here as i am new to sql statement
    I have 3 tables.
    Table1 :- TeamID, Team_Name, Team_Logo
    Table2:- TeamID, PlayerID
    Table3:- PlayerID, Player_Name
    How do i do a single select statement that select all information from table1 and the count of playerID from table2?
    My MS access table has relationships.
    One team can have many players. So how do it get the numbers of player in my team?
    Thanks.

    Thanks.
    but may i know why i have to max (a.team_name)???Actually there is no need of max() here, but it must be an aggregate function to use in this context. There is no harm in using it like this. This is a work around, I didn't get enough time to work on it.
    But as long as it gives correct result, don't worry about it.
    btw, how do i assign duke $$ to u?
    i am new to this forum.You can read at http://forum.java.sun.com/rewardFaq.jsp#assign
    Have a nice weekend.
    Sudha

  • Sql to get monthwise data

    Hi experts,
    I have a query to get data monthwise for a particular column value from this table
    SQL> desc doctor_patient_diagnosis_tab
    Name Null? Type
    DOCTOR_CODE VARCHAR2(8)
    VISIT_ID NUMBER(12)
    DIAGNOSIS VARCHAR2(2000)
    EMP_NO NUMBER(6)
    TRANSACTION_DATE DATE
    FINAL_TAG VARCHAR2(1)
    DIAGNOSIS_CODE VARCHAR2(8)
    in the following way to display......
    Diagnosis Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Total
    OTHER DISEASES 15 4 5 9 14 31 8 1 6 7 2 5 107
    ROUTINE DEWORMING 14 4 7 7 9 3 9 9 2 4 9 14 91
    my query is as follows.... but not giving me exact result
    select substr(diagnosis,1,20) diag,
    count(decode(TO_CHAR(transaction_date,'MON'),'JAN',VISIT_ID,0)) jan,
    count(decode(TO_CHAR(transaction_date,'MON'),'FEB',VISIT_ID,0)) feb,
    count(decode(TO_CHAR(transaction_date,'MON'),'MAR',VISIT_ID,0)) mar,
    count(decode(TO_CHAR(transaction_date,'MON'),'APR',VISIT_ID,0)) apr,
    count(decode(TO_CHAR(transaction_date,'MON'),'MAY',VISIT_ID,0)) may,
    count(decode(TO_CHAR(transaction_date,'MON'),'JUN',VISIT_ID,0)) jun,
    count(decode(TO_CHAR(transaction_date,'MON'),'JUL',VISIT_ID,0)) jul,
    count(decode(TO_CHAR(transaction_date,'MON'),'AUG',VISIT_ID,0)) aug,
    count(decode(TO_CHAR(transaction_date,'MON'),'SEP',VISIT_ID,0)) sep,
    count(decode(TO_CHAR(transaction_date,'MON'),'OCT',VISIT_ID,0)) oct,
    count(decode(TO_CHAR(transaction_date,'MON'),'NOV',VISIT_ID,0)) nov,
    count(decode(TO_CHAR(transaction_date,'MON'),'DEC',VISIT_ID,0)) dec
    from doctor_patient_diagnosis_tab
    WHERE to_char(transaction_date,'DD-MON-YYYY') >='01-JAN-2011'
    GROUP BY diagnosis
    ORDER BY 1;
    can someone assist me in this ...
    Thank you

    Hi kiran,
    It is helpful for me but not yet achieved the result, when I run the inner query it gives as.....
    SQL> select substr(diagnosis,1,20) diag,
    2 decode(TO_CHAR(transaction_date,'MON'),'JAN',VISIT_ID,0) jan,
    3 decode(TO_CHAR(transaction_date,'MON.'),'FEB',VISIT_ID,0) feb,
    4 decode(TO_CHAR(transaction_date,'MON'),'MAR',VISIT_ID,0) mar,
    5 decode(TO_CHAR(transaction_date,'MON'),'APR',VISIT_ID,0) apr,
    6 decode(TO_CHAR(transaction_date,'MON'),'MAY',VISIT_ID,0) may,
    7 decode(TO_CHAR(transaction_date,'MON'),'JUN',VISIT_ID,0) jun,
    8 decode(TO_CHAR(transaction_date,'MON'),'JUL',VISIT_ID,0) jul,
    9 decode(TO_CHAR(transaction_date,'MON'),'AUG',VISIT_ID,0) aug,
    10 decode(TO_CHAR(transaction_date,'MON'),'SEP',VISIT_ID,0) sep,
    11 decode(TO_CHAR(transaction_date,'MON'),'OCT',VISIT_ID,0) oct,
    12 decode(TO_CHAR(transaction_date,'MON'),'NOV',VISIT_ID,0) nov,
    13 decode(TO_CHAR(transaction_date,'MON'),'DEC',VISIT_ID,0)dec
    14 from doctor_patient_diagnosis_tab
    15 WHERE transaction_date >=to_date('01-JAN-2011','dd-mon-yyyy');
    DIAG JAN FEB MAR APR MAY
    JUN JUL AUG SEP OCT NOV DEC
    AMOEBIASIS 0 0 0 0 0
    3247 0 0 0 0 0 0
    test 200 0 0 0 0
    0 0 0 0 0 0 0
    AMOEBIASIS 0 0 0 0 0
    0 3414 0 0 0 0 0
    DIAG JAN FEB MAR APR MAY
    JUN JUL AUG SEP OCT NOV DEC
    AMOEBIASIS 0 0 0 0 0
    3359 0 0 0 0 0 0
    so one diag comes three times instead of in a single record.
    thanks

  • How to get max date in child table

    I have tow tables Departments as the master table and Employees as the child table
    The employees table (the child) has employee_hiring_date Field .
    I want to get the maximum hiring date in the employee table for every department to make validation over it.
    How to make this.

    It's more or less described in the doc I gave you.
    OK, lets do it with your sample.
    I assume you have accessors defined to navigate between the master and the detail (in both directions). The accessors on entity level are named
    "Employees1" to get the employees of a department
    "Departments1" to get the department of an employee
    1. In the Departments entity you add a transient attribute "MaxSalary" as type Number, select 'Expression' as 'Value Type' and type "Employees1.max("Salary")" in the value field. Make sure to uncheck the 'Persistent' attribute in the dialog. This will mark the attribute as transient.
    2. in the entity Employees open the 'Business Rules' and select the 'Saraly' attribute. Add a rule by clicking the green plus. 'Rule Type' is 'Compare', 'Operator' is 'LessOrEqualTo' and in the 'Compare With' drop down select 'Expression'. In the Dialog enter "Departments1.MaxSalary". Switchto the 'FailureHandling' tab and type in a message you like to see (e.g. 'The Salary is too high!") and save your work. The magic is done in the expression "Departments1.MaxSalary" which selects the department of the employee and gets the value of the attribute 'MaxSalary' which is an other Groovy expression which gets the max salary of all employees in the department.
    3. To get the 'MaxSalary' attribute from the entity to the view object, you can open the VO editor and select the 'Attributes' section. Click the arrow down right of green plus and select 'Add Attribute from Entity, shuffle the MaxSalary attribute you see in the Department entity to the right and save your work.
    If you now test the app in the Tester try changing the salary of an employee to a value higher then max of the department and you should see your error message.
    Timo

Maybe you are looking for

  • How can I separate FCPX projects and events on external drive?

    Hi there! I'm working on a Mac Pro with two drives. One drive contains the OSX and the second drive I use to store video media. I'm running FCPX 10.0.4. The Mac Pro is used in a teaching environment (i.e. creative suite, FCPX, iMovie, etc). Each tuto

  • Problem while downloading the data from servlet across SSL

    Hi All, I am trying to download the data with the help of servlet across https. The below mentioned settings work fine if the application is on http. httpservletresponse.setHeader("Cache-Control", ""); httpservletresponse.setHeader("pragma", ""); htt

  • After Updating my iPhone to the IOS 6.1.2 all of my iPhone music got erased

    Hey today I just updated my iPhone 4 software to the iOS 6.1.2 and then backed up my phone. I have everything back on my phone from before EXCEPT for all of the Music I had on my phone, GONE. All of my playlists, EVERYTHING. I backed up my iPhone aga

  • Partner functions relevant for interaction history

    Hello Experts, We want to register projects in our CRM system. One of the main requirements is that all partners involved in this project (both internal and external) and that the project is shown in all the BP's interaction history. We've copied sta

  • MB51 and BW Material Inventory 0IC_C03_Q0006 values do not match

    Hello BW experts, We recently implemented the standard material inventory extractors to our BW system.  When I compare the values between MB51 and 0IC_C03_Q0006, the quantities are the same but the values are different. For a particular material/plan