Help with "distint count" in query

Hi
I have a query that returns the following error:
ORA 00936: Missing Expression
and also after running it again
I get ORA 00900: Invalid SQL statement.
The query is as follows:
SELECT
        DISTINCT student_id,
        COUNT(student_id),
        ABSENCE_REASON_CODE,
        calendar_date,
        attendance_status,
        FROM AT_HOURLY_ATTENDANCE_RECORDS
        WHERE (absence_reason_code = 'UC')
       OR (absence_reason_code = '1');all help is gratefully acknowledged. Thanks in advance

Hi
Thanks to both guys for helping me out.. (Steven and Gasparatto)
The query still has the following problem:
ORA-00900: invalid SQL statement
I wonder why this is happening..
(Toad is pointing out student_id as a possible culprit
the code again is:
SELECT
        DISTINCT student_id,
        COUNT(student_id),
        ABSENCE_REASON_CODE,
        calendar_date,
        attendance_status  
        FROM AT_HOURLY_ATTENDANCE_RECORDS
        WHERE (absence_reason_code = 'UC')
       OR (absence_reason_code = '1');Please excuse me for my naive questions. I have learnt a lot today itself. Thanks a lot again

Similar Messages

  • Help with Converting an Access query

    Hello:
    First time poster and would appreciate some help in converting this Access query into T-SQL so I can use in a Stored Procedure. I don't need help in resolving the syntax for the variables as parameter in the second query, but stuck in writing the first query
    in T-SQL . I assume I need some type of nested query with a left join to another query in T-SQL. 
    How do I convert this from Access into MS-SQL
    SELECT TBL_MONTH.L_Month, TBL_MONTH.L_MonthName
    FROM TBL_MONTH LEFT JOIN qry_MonthCheck ON TBL_MONTH.L_Month = qry_MonthCheck.L_Month
    WHERE (((qry_MonthCheck.L_Month) Is Null));
    qryMonthCheck in Access is defined as
    SELECT TBL_MONTH.L_Month, TBL_SIGNOFF.SO_YEAR, TBL_SIGNOFF.SO_USER, TBL_SIGNOFF.SO_LOCATION
    FROM TBL_MONTH RIGHT JOIN TBL_SIGNOFF ON TBL_MONTH.L_Month = TBL_SIGNOFF.SO_MONTH
    WHERE (((TBL_SIGNOFF.SO_YEAR)=[forms]![frm_signoff]![cboyear]) AND ((TBL_SIGNOFF.SO_LOCATION)=[Tempvars]![tmpVarUserLOC]));

    It is very much up to personal taste. For tables I use no prefix at all. Or suffix. I prefer plural: categories, products, etc. For junction tables, I drop the plural in the first entity, for instance productcategories. As for the case, many people prefer
    initial uppercase, while I go for lowercase only. But initial uppercase has its points, particularly in documentation. I am a staunch advocate of using case-sensitive collation for metadata. I don't see any point in mixing productcategories, Productcategories,
    ProductCategories etc. That can only cause confusion.
    As for either entities, I don't use views much, and I don't have any prefix for these either. In fact, several views I've been involved used to be tables once upon a time.
    If you want to add a marker to the object name, I recommend using a suffix. It is much easier to find objects in the version control system and other browser, when not everything is cluttered on the same letter. For instance, I typically add _sp at the end
    of stored procedure names.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Help with a COUNT query...

    I have created the following tables:
    create table ZONE (
    ZoneNo number(2),
    State char(3),
    PRIMARY KEY (ZoneNo)
    create table SCHOOL (
    SchoolType char(1),
    SchoolNumber number(4),
    SchoolName char(40),
    SchoolZone number(2),
    PRIMARY KEY (SchoolNumber,SchoolType),
    FOREIGN KEY (SchoolZone) REFERENCES ZONE
    create table TEACHER (
    TeacherCode char(5),
    Surname char(30),
    FirstName char(30),
    Gender char(1),
    WorksFor number(4),
    YearCommenced number(4),
    LivesIn number(2),
    TeachingType char(1),
    PRIMARY KEY (TeacherCode),
    FOREIGN KEY (WorksFor, TeachingType) REFERENCES SCHOOL(SchoolNumber,SchoolType),
    FOREIGN KEY (LivesIn) REFERENCES ZONE
    create table COMPUTER (
    SerialNumber char(10),
    Description char(50),
    RegisteredTo char(5),
    PRIMARY KEY (SerialNumber),
    FOREIGN KEY (RegisteredTo) REFERENCES TEACHER
    My question is, how would i make a COUNT (or similar) query that would display each SchoolName and show the total amount of teachers who work at that school in the second column?

    Yes, it needs to join all columns on foreign key.
    This is usual, gentle, safety, and universal approach.
    insert into ZONE values (6,'CA');
    insert into SCHOOL values ('E',600,'Oracle Elemental School',6);
    insert into SCHOOL values ('J',600,'Oracle Middle School',6);
    insert into SCHOOL values ('S',600,'Oracle High School',6);
    insert into TEACHER values (12001,'Suzuki','Akiko','F',600, 2005, 6, 'E');
    insert into TEACHER values (12002,'Scott','Tiger','M',600, 2005, 6, 'E');
    insert into TEACHER values (12003,'Zhong','San','M',600, 2005, 6, 'J');
    insert into TEACHER values (12004,'Li','Si','M',600, 2005, 6, 'J');
    insert into TEACHER values (12005,'Wang','Wu','M',600, 2005, 6, 'J');
    insert into TEACHER values (12006,'Kim','Youngae','F',600, 2005, 6, 'S');
    insert into TEACHER values (12007,'Kim','Jiu','F',600, 2005, 6, 'S');
    insert into TEACHER values (12008, null,'Joe','M',600, 2005, 6, 'S');
    column schoolname format a30
    set lines 120
    select s.SchoolName
    ,count(*) "ALL"
    ,count(t.TeacherCode) "ALL(CODE)"
    ,count(distinct t.TeacherCode) "DISTINCT(CODE)"
    ,count(t.surname) "ALL(NAME)"
    ,count(distinct t.surname) "DISTINCT(NAME)"
    from School s, Teacher t
    where s.SchoolNumber = t.WorksFor
    and s.SchoolType = t.TeachingType
    group by s.SchoolName
    SCHOOLNAME                            ALL  ALL(CODE) DISTINCT(CODE)  ALL(NAME) DISTINCT(NAME)
    Oracle Elemental School                 2          2              2          2              2
    Oracle High School                      3          3              3          2              1
    Oracle Middle School                    3          3              3          3              3select s.SchoolName
    ,count(*) "ALL"
    ,count(t.TeacherCode) "ALL(CODE)"
    ,count(distinct t.TeacherCode) "DISTINCT(CODE)"
    ,count(t.surname) "ALL(NAME)"
    ,count(distinct t.surname) "DISTINCT(NAME)"
    from School s, Teacher t
    where s.SchoolNumber = t.WorksFor
    --and s.SchoolType = t.TeachingType
    group by s.SchoolName
    SCHOOLNAME                            ALL  ALL(CODE) DISTINCT(CODE)  ALL(NAME) DISTINCT(NAME)
    Oracle Elemental School                 8          8              8          7              6
    Oracle High School                      8          8              8          7              6
    Oracle Middle School                    8          8              8          7              6

  • Help with doing SELECT sub query within the SET of an UPDATE statement

    After doing some research, it appears as if it's possible to use a SELECT subquery in the SET of an UPDATE statement.  i did find some examples and here is my code, however when I click the "check" button it's saying the field (my entire select subquery) is unknown and neither in one of the specified tables or defined by a "DATA".  Do I have a syntax issue or is there another reason why it's not taking this as a valid statement?  Thanks for the help!
    LOOP AT IT_DATA
    UPDATE /BIC/AZDP_O0140
       SET /BIC/ZCOUNTER = (SELECT COUNT( DISTINCT MATERIAL )
                            FROM /BIC/AZDP_O0140
                            WHERE MATERIAL EQ IT_DATA-MATERIAL
                            GROUP BY MATERIAL).
    ENDLOOP.

    my Update does indeed have a WHERE clause but because of the issue i'm having, all my criteria in my WHERE is black text in the ABAP editor.  The editor doesn't even recognize the keywords "WHERE" or "EQ".  Below is my entire statement which contains all WHERE criteria in both the Update and the Subquery, i've just removed it for testing to help simplify the query and eliminate as many other factors as posisble that may be causing problems:
    LOOP AT IT_DATA.
       UPDATE /BIC/AZDP_O0140
       SET /BIC/ZCOUNTER = (SELECT COUNT( DISTINCT MATERIAL ) FROM /BIC/AZDP_O0140
       WHERE WHSE_NUM EQ IT_DATA-WAREHOUSE
        AND  PLANT EQ IT_DATA-PLANT
        AND  /BIC/ZTRAN_NO EQ IT_DATA-TRANS_NUM
        AND  DELIV_NUMB EQ IT_DATA-DELIVERY
        AND  MATERIAL EQ IT_DATA-MATERIAL
        GROUP BY MATERIAL)
       WHERE WHSE_NUM EQ IT_DATA-WAREHOUSE
        AND  PLANT EQ IT_DATA-PLANT
        AND  /BIC/ZTRAN_NO EQ IT_DATA-TRANS_NUM
        AND  DELIV_NUMB EQ IT_DATA-DELIVERY
        AND  MATERIAL EQ IT_DATA-MATERIAL.
    ENDLOOP.
    i should also mention the sources i found were not within the SAP Library but instead on other third-party ABAP websites.  so because i was having issues i wanted to post here to see if anyone else has come up with a working solution.  but if this cannot be done i can likely come up with a solution for my needs using multiple internal tables, this would just have been much easier since i can get a query like this to do what i want in SQL Server.  Thought i could utilize this in ABAP as well.

  • Need help with division within a query

    Hello all~
    I am trying to divide these two columns to get a % of case numbers involving an accident. Im pretty sure you need to use decode to avoid the divide by 0 error but not sure how to implement this within my query. When i run this query below, it gives me the result of "1", which is not correct. Can someone help me please?
    Oracle Version 10g
    ACCIDENT is a datatype VARCHAR
    CASE_NUMBER is a datatype VARCHAR
    select to_char(count(ACCIDENT),'999,999,999') as "ACCIDENT",
    to_char(COUNT(CASE_NUMBER),'999,999,999')as "CASE NUMBER",
    round(ratio_to_report(count(accident))
    OVER()*100,2)as "%"
    from      "PURSUIT"
    WHERE ACCIDENT = 'Y'
    AND
    (:P1_BEG_DATE IS NULL AND :P1_END_DATE IS NULL
    OR
    pursuit_date BETWEEN to_date(:p1_beg_date,'MM/DD/YYYY') and to_date
    (:p1_end_date,'MM/DD/YYYY'))
    AND(:P1_TROOP=pursuit.officer_troop OR :p1_troop IS NULL) 
    AND(:P1_RADIO=pursuit.officer_radio OR :p1_radio IS NULL)
    group by case_numberThanks
    Deanna

    Are you sure that the ANDs and ORs in your WHERE clause will take precedence properly?
    Also, if you always select only cases where there has been an accident, what percentage would you like to display? Surely in this case the percentage of cases involving in accident in cases where there was an accident.. is 100%?
    as a simpler example
    SELECT
      accident,
      ROUND(RATIO_TO_REPORT(count(*)) OVER() * 100)
    FROM
      pursuit
    GROUP BY
      accidentHere's a trick to neaten up those IS NULLs:
    SELECT
      accident,
      ROUND(RATIO_TO_REPORT(count(*)) OVER() * 100)
    FROM
      pursuit
    WHERE
      pursuit_date >= COALESCE(:p1_beg_date, pursuit_date) AND
      pursuit_date <= COALESCE(:p1_end_date, pursuit_date) AND
      officer_troop LIKE :p1_troop AND
      offcier_radio LIKE :p1_radio
    GROUP BY
      accidentTo wildcard a date, simply pass NULL in; the coalesce will replace the null with the pursuit_date from the record (thus the >= and <= becomes true)
    To wildcard the troop or the radio, simply pass a '%' symbol as the value of the parameter. If the front end code is already set up to pass nulls, use the COALESCE trick above

  • Help with aggregate function max query

    I have a large database which stores daily oil life, odo readings from thousands of vehicles being tested but only once a month.
    I am trying to grab data from one month where only the EOL_READ = 0 and put all of those values into the previous month's query where EOL_READ = anything.
    Here is the original query which grabs everything
    (select distinct vdh.STID, vdh.CASE_SAK,
    max(to_number(decode(COMMAND_ID,'EOL_READ',COMMAND_RESULT,-100000))) EOL_READ,
    max(to_number(decode(COMMAND_ID,'ODO_READ',COMMAND_RESULT,-100000))) ODO_READ,
    max(to_number(decode(COMMAND_ID,'OIL_LIFE_PREDICTION',COMMAND_RESULT,-100000))) OIL_LIFE_PREDICTION
    from veh_diag_history vdh, c2pt_data_history cdh
    where vdh.veh_diag_history_sak = cdh.veh_diag_history_sak
    and cdh.COMMAND_ID in ('EOL_READ','ODO_READ','OIL_LIFE_PREDICTION')
    and vdh.LOGICAL_TRIGGER_SAK = 3
    and cdh.CREATED_TIMESTAMP =vdh.CREATED_TIMESTAMP
    and cdh.CREATED_TIMESTAMP >= to_date('03/01/2007 12:00:00 AM','mm/dd/yyyy HH:MI:SS AM')
    and cdh.CREATED_TIMESTAMP < to_date('04/01/2007 12:00:00 AM','mm/dd/yyyy HH:MI:SS AM')
    group by vdh.STID, vdh.case_sak
    having count(distinct command_id) = 3
    order by OIL_LIFE_PREDICTION)
    which gives 5 columns:
    STID, CASE_SAK, EOL_READ, ODO_READ, and OIL_LIFE_PREDICTION
    and gives me about 80000 rows returned for the above query
    I only want one reading per month, but sometimes I get two.
    STID is the unique identifier for a vehicle.
    I tried this query:
    I tried this query which nests one request within the other and SQL times out every time:
    select distinct vdh.STID, vdh.CASE_SAK,
    max(to_number(decode(COMMAND_ID,'EOL_READ',COMMAND_RESULT,-100000))) EOL_READ,
    max(to_number(decode(COMMAND_ID,'ODO_READ',COMMAND_RESULT,-100000))) ODO_READ,
    max(to_number(decode(COMMAND_ID,'OIL_LIFE_PREDICTION',COMMAND_RESULT,-100000))) OIL_LIFE_PREDICTION
    from veh_diag_history vdh, c2pt_data_history cdh
    where vdh.veh_diag_history_sak = cdh.veh_diag_history_sak
    and cdh.COMMAND_ID in ('EOL_READ','ODO_READ','OIL_LIFE_PREDICTION')
    and vdh.LOGICAL_TRIGGER_SAK = 3
    and cdh.CREATED_TIMESTAMP =vdh.CREATED_TIMESTAMP
    and cdh.CREATED_TIMESTAMP >= to_date('02/01/2007 12:00:00 AM','mm/dd/yyyy HH:MI:SS AM')
    and cdh.CREATED_TIMESTAMP < to_date('03/01/2007 12:00:00 AM','mm/dd/yyyy HH:MI:SS AM')
    group by vdh.STID, vdh.case_sak
    having count(distinct command_id) = 3
    and vdh.stid in (select distinct vdh.STID, vdh.CASE_SAK,
    max(to_number(decode(COMMAND_ID,'EOL_READ',COMMAND_RESULT,-100000))) EOL_READ,
    max(to_number(decode(COMMAND_ID,'ODO_READ',COMMAND_RESULT,-100000))) ODO_READ,
    max(to_number(decode(COMMAND_ID,'OIL_LIFE_PREDICTION',COMMAND_RESULT,-100000))) OIL_LIFE_PREDICTION
    from veh_diag_history vdh, c2pt_data_history cdh
    where vdh.veh_diag_history_sak = cdh.veh_diag_history_sak
    and cdh.COMMAND_ID in ('EOL_READ','ODO_READ','OIL_LIFE_PREDICTION')
    and vdh.LOGICAL_TRIGGER_SAK = 3
    and cdh.CREATED_TIMESTAMP =vdh.CREATED_TIMESTAMP
    and cdh.CREATED_TIMESTAMP >= to_date('03/01/2007 12:00:00 AM','mm/dd/yyyy HH:MI:SS AM')
    and cdh.CREATED_TIMESTAMP < to_date('04/01/2007 12:00:00 AM','mm/dd/yyyy HH:MI:SS AM')
    group by vdh.STID, vdh.case_sak
    having count(distinct command_id) = 3
    and (max(to_number(decode(COMMAND_ID,'EOL_READ',COMMAND_RESULT,-100000)))) = 0)
    order by OIL_LIFE_PREDICTION
    so in summary I am trying to select values from the previous month only from those stids where this month's value for EOL_READ = 0
    Any ideas.....please help.

    You can use row_number() within each stid and each month to determine the first read of each month. Then you can use lag() to get the previous month's reading of the current month's reading is zero.
    with all_data as (
    select stid,
           case_sak,
           eol_read,
           timestamp,
           row_number() over (partition by stid, trunc(timestamp,'mm') order by timestamp) AS rn
      from veh_diag_history
    select stid,
           case_sak,
           case
             when eol_read = 0
               then lag(eol_read) over (partition by stid order by timestamp)
             else eol_read
           end as eol_read
      from all_data
    where rn = 1;

  • Help with Finding Duplicate records Query

    HI,
    I am trying to write a query that will find duplicate records/cases.
    This query will be used in a report.
    So, here are the requirements:
    I need to find duplicate cases/records based on the following fields:
    DOB, DOCKET, SENT_DATEI was able to do that with the following query. The query below is able to give me all duplicate records based on the Criteria above
    SELECT      DEF.BIRTH_DATE DOB,
               S.DOCKET DOCKET,
               S.SENT_VIO_DATE SENT_DATE, COUNT(*)
    FROM SENTENCES S,
                DEFENDANTS DEF
    WHERE      S.DEF_ID = DEF.DEF_ID
    AND       S.CASE_TYPE_CODE = 10
    GROUP BY  DEF.BIRTH_DATE, S.DOCKET, S.SENT_VIO_DATE
    HAVING COUNT(*) > 1;
    //I AM GOING TO CALL THIS QUERY 'X'Now, the information to be displayed on the report: defendants Name, DOB, District, Docket, Def Num, Sent Date, and PACTS Num if possible.
    The problem that I need help on is how to combine those queries together (what I mean is a sub query). the 'X' query returns multiple values. please have a look at the comments on the query below to see what I'm trying to achieve.
    here is the main query:
    SELECT      INITCAP(DEF.LAST_NAME) || ' ' || INITCAP(DEF.FIRST_NAME) || ' ' || INITCAP(DEF.MIDDLE_NAME) DEFENDANT_NAME,
            DEF.BIRTH_DATE DOB,
            TRIM(DIST.DISTRICT_NAME) DISTRICT_NAME,
            S.DOCKET DOCKET,
            S.DEF_NUM DEF_NUM,
            S.SENT_VIO_DATE SENT_DATE,
            DEF.PACTS_ID PACTS_NUM
    FROM      USSC_CASES.DEFENDANTS DEF,
            USSC_CASES.SENTENCES S,
            LOOKUP.DISTRICTS DIST
    WHERE      DEF.DEF_ID = S.DEF_ID
    AND      S.DIST_ID = DIST.USSC_DISTRICT_ID
    AND     S.CASE_TYPE_CODE = 10
    AND     S.USSC_ID IS NOT NULL
    AND // what i'm trying to do is: DOB, DOCKET, SENT_DATE IN ('X' QUERY), is this possible ??
    ORDER BY DEFENDANT_NAME; thanks in advance.
    I am using Oracle 11g, and sql developer.
    if my approach doesn't work, is there a better approach ?
    Edited by: Rooney on Jul 11, 2012 3:50 PM

    If I got it right, you want to join table USSC_CASES.DEFENDANTS to duplicate rows in USSC_CASES. If so:
    SELECT  INITCAP(DEF.LAST_NAME) || ' ' || INITCAP(DEF.FIRST_NAME) || ' ' || INITCAP(DEF.MIDDLE_NAME) DEFENDANT_NAME,
            DEF.BIRTH_DATE DOB,
            TRIM(DIST.DISTRICT_NAME) DISTRICT_NAME,
            S.DOCKET DOCKET,
            S.DEF_NUM DEF_NUM,
            S.SENT_VIO_DATE SENT_DATE,
            DEF.PACTS_ID PACTS_NUM
      FROM  USSC_CASES.DEFENDANTS DEF,
             SELECT  *
               FROM  (
                      SELECT  S.*,
                              COUNT(*) OVER(PARTITION BY DEF.BIRTH_DATE, S.DOCKET, S.SENT_VIO_DATE) CNT
                        FROM  USSC_CASES.SENTENCES S
               WHERE CNT > 1
            ) S,
            LOOKUP.DISTRICTS DIST
      WHERE DEF.DEF_ID = S.DEF_ID
       AND  S.DIST_ID = DIST.USSC_DISTRICT_ID
       AND  S.CASE_TYPE_CODE = 10
       AND  S.USSC_ID IS NOT NULL
      ORDER BY DEFENDANT_NAME;If you want to exclude duplicates from the query and do not care which row out of duplicate rows to choose:
    SELECT  INITCAP(DEF.LAST_NAME) || ' ' || INITCAP(DEF.FIRST_NAME) || ' ' || INITCAP(DEF.MIDDLE_NAME) DEFENDANT_NAME,
            DEF.BIRTH_DATE DOB,
            TRIM(DIST.DISTRICT_NAME) DISTRICT_NAME,
            S.DOCKET DOCKET,
            S.DEF_NUM DEF_NUM,
            S.SENT_VIO_DATE SENT_DATE,
            DEF.PACTS_ID PACTS_NUM
      FROM  USSC_CASES.DEFENDANTS DEF,
             SELECT  *
               FROM  (
                      SELECT  S.*,
                              ROW_NUMBER() OVER(PARTITION BY DEF.BIRTH_DATE, S.DOCKET, S.SENT_VIO_DATE ORDER BY 1) RN
                        FROM  USSC_CASES.SENTENCES S
               WHERE RN = 1
            ) S,
            LOOKUP.DISTRICTS DIST
      WHERE DEF.DEF_ID = S.DEF_ID
       AND  S.DIST_ID = DIST.USSC_DISTRICT_ID
       AND  S.CASE_TYPE_CODE = 10
       AND  S.USSC_ID IS NOT NULL
      ORDER BY DEFENDANT_NAME;SY.

  • Help with re-writing this query

    Dear experts;
    create table t2
      ID varchar2(1000),
      name varchar2(1000),
       place varchar2(1000)
    create table mappingt2
      grades varchar2(1000)
      individual varchar2(1000)
    insert into t2 values ('James', 'John', 'newyork');
    insert into t2 values ('Linda', 'James', 'London');
    insert into t2 values ('Alex', 'kim', 'Mexico');
    insert into t2 values ('karen', 'Jack', 'Tunis');
    insert into t2 values ('CC', 'Jack', 'Peru');
    insert into t2 values ('Linda', 'James', 'Germany');
    insert into mappingt2 values ('A', 'James');
    insert into mappingt2 values ('C', 'Kim');
    insert into mappingt2 values ('C', 'Linda');
    insert into mappingt2 values ('B', 'CC');I have the following query below
    SELECT (select grades from mappingt2 t
       where t.individual =  pt.ID) as current_grade
          ,(select grades from mappingt2 ty
       where ty.individual =  pt.name) alt_grade
          ,pt.place
      FROM t2 ptI was just wondering whether this query can be better written. All help is appreciated. Thank you

    user13328581 wrote:
    Hi Frank, Tom Kyte claims sub scalar queries is usually betterHe didn't say usually he said if you want the first row faster
    >
    if your goal is to optimize your query for initial response time, you may want to use the former query, with the scalar subquery, because Oracle Database would have to get just the first row from DEPT, run the scalar subquery (select count...) against EMP to get the count, and then return it. The process for returning that first row would be very fast.
    >
    The corollary to this that was not explicitly mentioned in the article that I can see is that this probably comes at the expense of the time taken to return all the rows which can then take longer.

  • Need some help with a counting function

    Hello,
    I use a simple sheet to organize the timetable of my patients. Now I'd like to count how many different patients I attend, without counting a patient twice if I attend him twice a week for example. My sheet looks like this:
    Mon
    Tue
    Wed
    Thu
    John
    Steve
    John
    Wesley
    Mary
    Harry
    Deborah
    Peter
    Arnold
    Carol
    Chris
    Mary
    Sarah
    Karen
    Karen
    Carol
    Larry
    Peter
    So the answer would be 13, because I attend 13 different patients a week. Fields in blank should no be counted, the cell contend changes frequently.
    A friend of mine tried to help me with a countif function but it didn't work out for me, it would count the fields left blank too.
    Any idea?
    Thanks, gabriel

    Hi Gabriel,
    Here's another, more generalized, approach that doesn't need adjusting for maximum number of visits/week at the cost of just a few more formulas.  But only two tables!
    Formula in A2 and copied down:
      =ROUNDUP((ROW(cell)−1)÷$B$27,0)
    Formula in B2 and copied down:
      =IF(MOD(ROW(cell)−1,$B$27)=0,$B$27,MOD(ROW(cell)−1,$B$27))
    The formula in C2 and copied down:
      =OFFSET(Schedule::$A$1,0,B−1)
    The formula in D2 and copied down:
      =IFERROR(OFFSET(Schedule::$A$1,A2,B2−1,rows,columns),"")
    The formula in E2 and copied down:
      =IF(AND(D2≠0,LEN(D2)>0),COUNTIF($D$1:D2,D2),"")
    The formula in F2 and copied down:
      =IFERROR(IF(E=1,1,""),"")
    The formula in F27:  =SUM(F)
    The value in B27 is 4, the number of day columns in the Schedule table. You would change that if you increase or decrease the number of days on which you see patients.
    Column C is cosmetic, not needed in the calculation.
    The error triangle means all of the cells in the Schedule table are already accounted for in the rows above.
    Probably more compact ways to do this but it gets the job done.
    SG

  • Need Help with Creating the SQl query

    Hi,
    SQL query gurus...
    INFORMATION:
    I have two table, CURRENT and PREVIOUS.(Table Defs below).
    CURRENT:
    Column1 - CURR_PARENT
    Column2 - CURR_CHILD
    Column3 - CURR_CHILD_ATTRIBUTE 1
    Column4 - CURR_CHILD_ATTRIBUTE 2
    Column5 - CURR_CHILD_ATTRIBUTE 3
    PREVIOUS:
    Column1 - PREV_PARENT
    Column2 - PREV_CHILD
    Column3 - PREV_CHILD_ATTRIBUTE 1
    Column4 - PREV_CHILD_ATTRIBUTE 2
    Column5 - PREV_CHILD_ATTRIBUTE 3
    PROBLEM STATEMENT
    Here the columns 3 to 5 are the attributes of the Child. Lets assume that I have two loads, One Today which goes to the CURRENT table and one yesterday which goes to the PREVIOUS table. Between these two loads there is a CHANGE in the value for Columns either 3/4/5 or all of them(doesnt matter if one or all).
    I want to determine what properties for the child have changed with the help of a MOST efficient SQL query.(PARENT+CHILD is unique key). The Database is ofcourse ORACLE.
    Please help.
    Regards,
    Parag

    Hi,
    The last message was not posted by the same user_name that started the thread.
    Please don't do that: it's confusing.
    Earlier replies give you the information you want, with one row of output (maximum) per row in current_tbl. There may be 1, 2 or 3 changes on a row.
    You just have to unpivot that data to get one row for every change, like this:
    WITH     single_row  AS
         SELECT     c.curr_parent
         ,     c.curr_child
         ,     c.curr_child_attribute1
         ,     c.curr_child_attribute2
         ,     c.curr_child_attribute3
         ,     DECODE (c.curr_child_attribute1, p.prev_child_attribute1, 0, 1) AS diff1
         ,     DECODE (c.curr_child_attribute2, p.prev_child_attribute2, 0, 2) AS diff2
         ,     DECODE (c.curr_child_attribute3, p.prev_child_attribute3, 0, 3) AS diff3
         FROM     current_tbl    c
         JOIN     previous_tbl   p     ON  c.curr_parent     = p.prev_parent
                                AND c.curr_child     = p.prev_child
         WHERE     c.curr_child_attribute1     != p.prev_child_attribute1
         OR     c.curr_child_attribute2     != p.prev_child_attribute2
         OR     c.curr_child_attribute3     != p.prev_child_attribute3
    ,     cntr     AS
         SELECT     LEVEL     AS n
         FROM     dual
         CONNECT BY     LEVEL <= 3
    SELECT     s.curr_parent     AS parent
    ,     s.curr_child     AS child
    ,     CASE     c.n
              WHEN  1  THEN  s.curr_child_attribute1
              WHEN  2  THEN  s.curr_child_attribute2
              WHEN  3  THEN  s.curr_child_attribute3
         END          AS attribute
    ,     c.n          AS attribute_value
    FROM     single_row     s
    JOIN     cntr          c     ON     c.n IN ( s.diff1
                                    , s.diff2
                                    , s.diff3
    ORDER BY  attribute_value
    ,            parent
    ,            child
    ;

  • Help with SYSDATE in SQL query

    Hi all,
    I'm trying to select some data from table base on SYSDATE. The below query does not return any data.
    My query is:
    select count(TICKET_ID) "ECEMEA" from QTMT_TICKETS where STATUS_ID=1 and TEAM_ID=3 and RECEIVED_DATE=sysdate
    Could you please let me know, why this does not work? Date format in my application is: DD-MMM-YY (16-AUG-12). In the database the dates are stored in this format: MM/DD/YYYY (08/25/2012). Does it mean, that I have to play with the format?
    Please let me know.
    Thank you and best regards,
    Vladimir

    user13277783 wrote:
    Hi all,Please update your forum profile with a real handle instead of "user13277783".
    I'm trying to select some data from table base on SYSDATE. The below query does not return any data.
    My query is:
    select count(TICKET_ID) "ECEMEA" from QTMT_TICKETS where STATUS_ID=1 and TEAM_ID=3 and RECEIVED_DATE=sysdate
    Always post code wrapped in <tt>\...\</tt> tags, as described in the FAQ.
    Could you please let me know, why this does not work? Date format in my application is: DD-MMM-YY (16-AUG-12). In the database the dates are stored in this format: MM/DD/YYYY (08/25/2012). Assuming RECEIVED_DATE is actually of type DATE (and it should be), then no format is applied to dates until they are converted for display, however there may be a time component stored that is not visible in the default date display format. Try
    select count(TICKET_ID) "ECEMEA"
    from QTMT_TICKETS
    where STATUS_ID=1
    and TEAM_ID=3
    and RECEIVED_DATE >= trunc(sysdate)
    and RECEIVED_DATE < trunc(sysdate) + 1

  • Help with a "save as" query or an alternative suggestion

    Hi all
    Hope someone can spread some light on this for me, im rather new to using adobe pro - and never ventured into java scripts as yet..
    I have created a pdf document with various text boxes within the document. The document will be pushed out to external users who will only have access to adobe reader.
    My query is this:
    I've created a save button, but can the file name automatically be set to include the data in one of the text fields. I still want the user to chose where to save the document but want the file name to be fixed to the data in the relevant text box.
    If it can be done is it a relatively straight forward procedure.
    If this is not possible, then as an alternative is it possible ible to create maybe a Warning or pop up box after clicking on the "save as" button to prompt the user to save with a different file name to avoid saving over previous versions etc.
    Again if this is this possible, is it difficult to achieve?
    Many thanks in advance for any help!
    Cheers
    Adam

    This tutorial contains a lot of information about saving a file in Acrobat
    using JavaScript:
    http://acrobatusers.com/tutorials/how-save-pdf-acrobat-javascript
    The bottom line is that in order to do it you must have a script installed
    on the local machine.
    The alert is possible, but at the moment it is displayed the user can no
    longer cancel the save command, so you can't really tell them to cancel it
    at that time...

  • Help with supply and demand query using monthly buckets

    I'm working on a query bound for Discoverer which pulls the aggregated supply and demand for an item and buckets it into months. So for any given item, I need to show the item, onhand, cost, aggregated supply (planned orders, requisitions, pos), and aggregated demand (planned order demand, jobs) - all bucketed by months.
    The code below works okay to find all of the data for July, but I also need to show August and September. I'm thinking I could use a union but am reluctant because the query already runs kind of slow and I'm not sure if I'm on the right track.
    Database Server
    RDBMS : 10.2.0.3.0
    Oracle Applications : 11.5.9
    -Tracy
    select
          item.inventory_item_id, item.organization_code, item.item, item.description
        , item.make_buy,item.planner_code
        , planned.compile_designator, planned.order_type_text, sum(planned.quantity_rate)planned_total
        , planned.mrp_sugg_due_month
        , sum(job.required_quantity-job.quantity_issued)job_open, job.required_month
        , onhand.total_qoh
        , purchase.item_revision prev, purchase.promised_month, purchase.ship_to_organization_id 
        , sum((purchase.quantity-purchase.quantity_cancelled)-purchase.quantity_received)po_open  
        , req.item_revision rrev, req.destination_organization_id, req.org_id, req.need_by_month
        , sum((req.quantity-req.quantity_cancelled)-req.quantity_delivered)req_open
        , cost.item_cost,cost.cost
    from
    --item--
    (select mtl.inventory_item_id, mtl.segment1 item,mtl.description,decode(mtl.planning_make_buy_code,1,'Make',2,'Buy') make_buy
            ,mtl.organization_id, mtp.organization_code, mtl.planner_code
           ,to_char(add_months(sysdate,+1),'YYYY_MM')month1, to_char(add_months(sysdate,+2),'YYYY_MM')month2
           ,to_char(add_months(sysdate,+3),'YYYY_MM')month3
    from    inv.mtl_system_items_b mtl, inv.mtl_parameters mtp
    where    mtl.organization_id = mtp.organization_id
    )item,
    --planned orders - 3 months --
    (select compile_designator,organization_id,inventory_item_id,order_type_text,nvl(quantity_rate,0)quantity_rate,new_due_date
           ,to_char(trunc(new_due_date,'MM'),'YYYY_MM')mrp_sugg_due_month
    from   apps.mrp_orders_sc_v
    where  order_type_text in ('Planned order','Planned order demand')
    and    to_char(trunc(new_due_date,'MM'),'YYYY_MM') <= to_char(add_months(:Month,+2),'YYYY_MM')
    and    to_char(trunc(new_due_date,'MM'),'YYYY_MM') >=  to_char(:Month,'YYYY_MM')
    )planned,
    --jobs - 3 months--
    (select organization_id,wip_entity_name job, inventory_item_id,concatenated_segments,nvl(required_quantity,0)required_quantity
            ,nvl(quantity_issued,0)quantity_issued, date_required,to_char(trunc(date_required,'MM'),'YYYY_MM') required_month
            ,wip_entity_id,creation_date, wip_job_status
    from    apps.wip_requirement_ops_inq_v
    where   primary_item_id <>inventory_item_id
    and     wip_job_status not in ('Closed','Cancelled','Complete')
    and     to_char(trunc(date_required,'MM'),'YYYY_MM') <= to_char(add_months(:Month,+2),'YYYY_MM')
    and     to_char(trunc(date_required,'MM'),'YYYY_MM') >= to_char(:Month,'YYYY_MM')
    )job,
    --qty onhand--
    (select  inventory_item_id,organization_id,sum(nvl(transaction_quantity,0))total_qoh
    from     inv.mtl_onhand_quantities_detail
    group by inventory_item_id, organization_id
    )onhand,
    -- po - 3 months--
    (select pol.item_id, pol.item_revision, nvl(pll.quantity,0)quantity, nvl(pll.quantity_received,0)quantity_received
          , nvl(pll.quantity_rejected,0),nvl(pll.quantity_cancelled,0)quantity_cancelled,poh.segment1 po_num
           ,pll.promised_date, to_char(trunc(pll.promised_date,'MM'),'YYYY_MM')promised_month
           ,pll.shipment_num,pll.ship_to_organization_id 
    from   po.po_lines_all pol, po.po_headers_all poh, po.po_line_locations_all pll
    where  poh.po_header_id = pol.po_header_id
    and    pol.po_header_id = pll.po_header_id
    and    pol.po_line_id = pll.po_line_id
    and    pol.cancel_flag != 'Y'
    and    pol.item_id is not null
    and    to_char(trunc(pll.promised_date,'MM'),'YYYY_MM')<= to_char(add_months(:Month,+2),'YYYY_MM')
    and    to_char(trunc(pll.promised_date,'MM'),'YYYY_MM')>=  to_char(:Month,'YYYY_MM')
    )purchase,
    --reqs - 3 months--
    (select prh.segment1 req_number,nvl(prl.quantity,0)quantity,nvl(prl.quantity_delivered,0)quantity_delivered
           ,nvl(prl.quantity_cancelled,0)quantity_cancelled
           ,prl.destination_organization_id,prl.org_id,prl.item_id,prl.item_revision,prl.need_by_date
           ,to_char(trunc(prl.need_by_date,'MM'),'YYYY_MM')need_by_month
    from   po.po_requisition_headers_all prh, po.po_requisition_lines_all prl
    where  prh.requisition_header_id = prl.requisition_header_id(+)
    and    nvl(prl.cancel_flag,'N') !='Y'
    and    prh.authorization_status != 'CANCELLED'
    and    to_char(trunc(prl.need_by_date,'MM'),'YYYY_MM') <= to_char(add_months(:Month,+2),'YYYY_MM')
    and    to_char(trunc(prl.need_by_date,'MM'),'YYYY_MM') >=  to_char(:Month,'YYYY_MM')
    )req,
    --cost--
    (select msib.inventory_item_id,msib.organization_id,cqm.material_cost,cic.item_cost
    ,(case when cqm.material_cost=0 then cic.item_cost else cqm.material_cost end) cost, cqm.cost_group_id
    from inv.mtl_system_items_b msib
         ,(select cql.cost_group_id,cql.inventory_item_id,cql.organization_id,cql.layer_quantity,cql.material_cost,mp.organization_code
             from bom.cst_quantity_layers cql, inv.mtl_parameters mp
            where mp.default_cost_group_id = cql.cost_group_id) cqm
        ,bom.cst_item_costs cic
    where msib.inventory_item_id = cqm.inventory_item_id(+)
    and msib.organization_id = cqm.organization_id(+)
    and msib.inventory_item_id = cic.inventory_item_id(+)
    and msib.organization_id = cic.organization_id(+)
    )cost
    where item.inventory_item_id = job.inventory_item_id(+)
    and   item.organization_id = job.organization_id(+)
    and   item.month1 = job.required_month(+)  -- 2009_07 --
    and   item.inventory_item_id = onhand.inventory_item_id(+)
    and   item.organization_id = onhand.organization_id(+)
    and   item.inventory_item_id = purchase.item_id(+)
    and   item.month1 = purchase.promised_month(+)  -- 2009_07 --
    and   item.inventory_item_id = req.item_id(+)
    and   item.month1 = req.need_by_month(+)  -- 2009_07 --
    and   item.inventory_item_id = cost.inventory_item_id(+)
    and   item.organization_id = cost.organization_id(+)
    and   item.inventory_item_id = planned.inventory_item_id(+)
    and   item.organization_id = planned.organization_id(+)
    and   item.month1 = planned.mrp_sugg_due_month(+)  -- 2009_07 --
    and   item.make_buy = 'Buy'
    and   item.item in ('161309040','744L755','150-GFM') --test items --
    group by item.inventory_item_id,item.organization_code,item.item,item.description,item.make_buy,item.planner_code
          ,job.required_month ,onhand.total_qoh , purchase.item_revision,  purchase.promised_month
            ,purchase.ship_to_organization_id  ,cost.item_cost,cost.cost
           ,req.item_revision, req.destination_organization_id,req.org_id,req.need_by_month
           ,planned.compile_designator,planned.order_type_text,planned.mrp_sugg_due_month
    order by item.organization_code,item.item

    Hi,
    Six things:
    (1) Where are the one-to-many relationships between your tables? If a single row in mtl can match two (or more) rows in mrp, and can also match two (or more) rows in wip, then it looks like, when you join both of them them, you'll have a chasm trap, that is, you'll get all the matching rows from mrp paired with all matching rows from wip. Are you sure your existing query is producing the right results?
    Are there one-to-many relationships with the other tables in your original query?
    (2) Are your DATEs always at midnight? If not, avoid using BETWEEN and LAST_DAY for DATE comparisons: otherwise you'll miss everything between 00:00:01 and 23:59:59 on the last day.
    That is, instead of
    and     mrp.new_due_date(+) BETWEEN :Month AND LAST_DAY(ADD_MONTHS(:Month,2))ypou should say
    and       mrp.new_due_date (+)     >= :Month
    and       mrp.new_due_date (+)     <  ADD_MONTHS (:Month, 3)(3) The basic way to pivot the months of mrp_due_date is:
    SELECT    ...
    ,       NVL ( SUM ( CASE
                     WHEN  mrp.new_due_date >= :month
                     AND   mrp.new_due_date < ADD_MONTHS (:month, 1)
                     THEN  mrp.quantity_rate
                    END
               , 0
               )          AS mrp_qty_0
    ,       NVL ( SUM ( CASE
                     WHEN  mrp.new_due_date >= ADD_MONTHS (:month, 1)
                     AND   mrp.new_due_date <  ADD_MONTHS (:month, 2)
                     THEN  mrp.quantity_rate
                    END
               , 0
               )          AS mrp_qty_1When you do this, do not GROUP BY TRUNC (mrp.new_due_date, 'MM').
    The code above does two months: I'm sure you get the idea for how to do more.
    To get dynamic column headings (such as Jun_2009 or "2009-06" instead of the generic mrp_qty_o) requires dynamic SQL. The best way to do dynamic SQL depends on the tool that is producing the query (e.g. SQL*Plus). What are you using? Are you willing to change, if it helps?
    (4) Displaying separate columns from one row as a single column on multiple rows is called unpivoting. How badly do you want to do that? Your query would be simpler and faster if the output had only one row per group (rather than one row for mrp_qty and another row for wip_wty). That one row could have six columns (e.q. June_mrp, June_wip, July_mrp, July_wip, August_mrp and August_wip) instead of three. Depending on your front-end tool, you might even be able to wrap the single row of output so that it always appeared as two rows, each with three columns.
    (5) Sorry I told you to do
    and     mrp.order_type_text(+) in (...)I never use the + outer-join notation any more, so I forgot about the ORA-01719 error. There's no problem having an outer-join condition like that using ANSI notation. (One more reason to switch.)
    (6) As you noticed, this site doesn't like to print the &lt;&gt; inequality operator, even inside tags.
    Use the equivalent != operator instead, when posting on this site.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Continuation-Please help with a complex sql query

    Hi all,
    Thanks a lot for your suggestions and inputs in the last thread of this post.
    With the help of your suggested approach,i went ahead and was able to get some more data in the format as needed..I worked on gradually adding one table after another exactly as the data is required stepwise.But,still I am facing issues with displaying them.
    there are many issues I am not able to do and would appreciate if you please have a look at my latest modified SELECT given below and help me writing it to get the display as needed.
    Below,is the attempted query i tried out using your inputs.But,am stuck and need your help in writing it.
    **Here,there is 1 ->MANY lines for the t_objective_id--->This has many learning_record_ids which i want to group by the unique objective_id.
    Also,prior to that,there is a tplan_id---->which has MANY t_objective_id's
    SELECT DECODE (LAG (firstname, 1, 0) OVER (ORDER BY firstname),
                   firstname, ' ',
                   firstname
                  ) firstname,
           DECODE (LAG (emplid, 1, 0) OVER (ORDER BY emplid),
                   emplid, ' ',
                   emplid
                  ) emplid,
           DECODE (LAG (tplan_name, 1, 0) OVER (ORDER BY tplan_name),
                   tplan_name, ' ',
                   tplan_name
                  ) tplan_name,
                  tplan_id,
                  DECODE (LAG (activities, 1, 0) OVER (ORDER BY activities),
                   activities, ' ',
                   activities
                  ) activities,
                  activities,
                  --activities,
           DECODE (LAG (t_objective_id, 1, 0) OVER (ORDER BY t_objective_id),
                   t_objective_id, ' ',
                   t_objective_id
                  ) t_objective_id,           
                   completed_activities,required_credits,
          DECODE (LAG (learning_record_id, 1, 0) OVER (ORDER BY learning_record_id),
                   learning_record_id, ' ',
                   learning_record_id
                  ) learning_record_id,           
                   catalog_item_name,catalog_item_type           
      FROM (SELECT test_cp.firstname, test_op.emplid, tp.tplan_name,tp.tplan_id,FN_TP_GET_CMPLTD_ACT_CNT(tp.tplan_id,test_lp.lp_person_id,'1862') activities,
                   test_tpo.t_objective_id,
                   (  fn_tp_obj_comp_req_act_cdt (test_lp.lp_person_id,
                                                  tp.tplan_id,
                                                  test_tpo.t_objective_id,
                                                  tp.is_credit_based
                    + fn_tp_obj_comp_opt_act_cdt (test_lp.lp_person_id,
                                                  tp.tplan_id,
                                                  test_tpo.t_objective_id,
                                                  tp.is_credit_based
                   ) completed_activities,test_tpo.required_credits,lr.learning_record_id,lr.catalog_item_name,lr.catalog_item_type
              FROM test_learning_plan test_lp,
                   test_training_plan tp,
                   test_person test_cp,
                   test_org_person test_op,test_tp_learning_activity test_tplplr,
                   test_tp_objective test_tpo,test_learning_record lr,test_train_obj_activity tpobjact
             WHERE test_lp.lp_person_id = '1862188559'
               AND test_cp.person_id = test_lp.lp_person_id
               AND tp.tplan_id = 'tplan200811200632352287621599'
               AND test_tpo.t_objective_id = tpobjact.t_objective_id
               AND test_lp.LP_CATALOG_HIST_ID = tp.tplan_id
               AND test_tplplr.tp_lp_lr_id =test_lp.learning_plan_id
               AND test_tplplr.activity_lp_lr_id = lr.learning_record_id
               AND lr.LR_CATALOG_HISTORY_ID = tpobjact.activity_id
               AND test_op.o_person_id = test_cp.person_id
               AND test_tpo.tplan_id = tp.tplan_id)
    If we see the outer SELECT ---then one of the main issues is for EACH t_objective_id----->There are n learning_record_ids.
    But,this select only shows 1 learning_record_id for each objective_id which is wrong.
    Similarly,the data displayed isnot proper.
    Below is the way I am getting the data now from the above SELECT.
    Note:- FIRSTNAME is not correctly displayed.
    FIRSTNAME     EMPLID     TPLAN_NAME     TPLAN_ID     ACTIVITIES     ACTIVITIES_1  
                      001                TP1          tplan1          5          5
    TESTNAME                                              tplan1           5          
    Continuation of the other columns of the same rows--**couldnt paste it properly so.
    T_OBJECTIVE_ID     COMPLETED_ACTIVITIES     REQUIRED_CREDITS     LEARNING_RECORD_ID        CATALOG_ITEM_NAME     CATALOG_ITEM_TYPE
              obj1               1                         5                         lr1                            C1                          Course
                    obj2               4                        4          

    Something like this might solve your problem ->
    satyaki>
    satyaki>select * from v$version;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Prod
    PL/SQL Release 10.2.0.1.0 - Production
    CORE    10.2.0.1.0      Production
    TNS for Linux: Version 10.2.0.1.0 - Production
    NLSRTL Version 10.2.0.1.0 - Production
    Elapsed: 00:00:00.00
    satyaki>
    satyaki>
    satyaki>select * from emp;
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7521 WARD       SALESMAN        7698 22-FEB-81     226.88        500         30
          7654 MARTIN     SALESMAN        7698 28-SEP-81       1815       1400         30
          7788 SCOTT      ANALYST         7566 19-APR-87     598.95                    20
          7839 KING       PRESIDENT            17-NOV-81       7260                    10
          7844 TURNER     SALESMAN        7698 08-SEP-81       2178          0         30
          7876 ADAMS      CLERK           7788 23-MAY-87     159.72                    20
          7900 JAMES      CLERK           7698 03-DEC-81     1379.4                    30
          7902 FORD       ANALYST         7566 03-DEC-81    5270.76                    20
          7934 MILLER     CLERK           7782 23-JAN-82     1887.6                    10
          7566 Smith      Manager         7839 23-JAN-82       1848          0         10
          7698 Glen       Manager         7839 23-JAN-82       1848          0         10
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7599 BILLY      ANALYST         7566 10-JUN-09       4500                    30
    12 rows selected.
    Elapsed: 00:00:00.00
    satyaki>
    satyaki>
    satyaki>
    satyaki>
    satyaki>select decode(lag(job,1,null) over(order by job),'CLERK','CK',
      2                                                   'SALESMAN', 'SM',
      3                                                   'ANALYST','AL',
      4                                                   'BO') res
      5  from emp;
    RE
    BO
    AL
    AL
    AL
    CK
    CK
    CK
    BO
    BO
    BO
    SM
    RE
    SM
    12 rows selected.
    Elapsed: 00:00:00.01
    satyaki>
    satyaki>
    satyaki>select MAX(decode(lag(job,1,null) over(order by job),'CLERK','CK',
      2                                                   'SALESMAN', 'SM',
      3                                                   'ANALYST','AL',
      4                                                   'BO')) res
      5  from emp;
    select MAX(decode(lag(job,1,null) over(order by job),'CLERK','CK',
    ERROR at line 1:
    ORA-30483: window  functions are not allowed here
    Elapsed: 00:00:00.01
    satyaki>
    satyaki>select MAX(res)
      2  from (
      3          select decode(lag(job,1,null) over(order by job),'CLERK','CK',
      4                                                           'SALESMAN', 'SM',
      5                                                           'ANALYST','AL',
      6                                                           'BO') res
      7          from emp
      8     );
    MA
    SM
    Elapsed: 00:00:00.00
    satyaki>
    satyaki>Regards.
    Satyaki De.

  • Help with a simple XMLTable query

    Newbie Oracle XML developer here and need a little guidance on how to retrieve multiple records in an xmltype table using xmltable.
    My document in the xmltype table looks like this:
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <echoems:ECHOMetrics xmlns:echoems="http://myURL/myFilename.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://myURL/myFilename.xsd
    http://myURL/myFilename.xsd">
    <OrderMetrics>
    <OrderItemMetric>
    <requestor>user1</requestor>
    <product>123</product>
    </OrderItemMetric>
    <OrderItemMetric>
    <requestor>0.0.0.0</requestor>
    <product>ABC</product>
    </OrderItemMetric>
    <OrderItemMetric>
    <requestor>user3</requestor>
    <product>XYZ</product>
    </OrderItemMetric>
    </OrderMetrics>
    </echoems:ECHOMetrics>
    I want to get all the products:
    Product
    123
    ABC
    XYZ
    I know to use XMLTable but am not sure how exactly to write it. If just one record, the following worked fine:
    select extractvalue
    (object_value,
    'echoems:ECHOMetrics/OrderMetrics/OrderItemMetric/product',
    'xmlns:echoems="http://myURL/myFilename.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
    ) object_value
    from echoXML;
    But with multiple records, I'm trying XMLTable but can't get it right. Trying something like this:
    select m.product
    from echoXML3
    xmlTable(
    (object_value,'echoems:ECHOMetrics/OrderMetrics/OrderItemMetric/*','xmlns:echoems="http://myURL/myFilename.xsd')
    passing object_value
    COLUMNS
    product varchar2(85) path 'product') m;
    Thanks in advance for any help on this.

    One more question. Instead of putting the xml doc in the query, how do I reference it from the xmlType table?
    You have:
    select *
    from xmltable
    '//OrderMetrics/OrderItemMetric'
    passing xmltype(
    '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <echoems:ECHOMetrics xmlns:echoems="http://myURL/myFilename.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://myURL/myFilename.xsd">
    <OrderMetrics>
    <OrderItemMetric>
    <requestor>user1</requestor>
    <product>123</product>
    </OrderItemMetric>
    <OrderItemMetric>
    <requestor>0.0.0.0</requestor>
    <product>ABC</product>
    </OrderItemMetric>
    <OrderItemMetric>
    <requestor>user3</requestor>
    <product>XYZ</product>
    </OrderItemMetric>
    </OrderMetrics>
    </echoems:ECHOMetrics>')
    columns
    prod varchar2(20) path 'product',
    requestor varchar(50) path 'requestor'
    However, the xmlDocument is already in an xmlType table called echoXML3 based on the xsd. I'm just trying to query it to get a relational result set. How, in the query above, do I replace the hardcoded xmlDoc with the xmlDoc located in my xmlType table?
    I thought maybe something like this but it's not working:
    select *
    from xmltable
    '//OrderMetrics/OrderItemMetric'
    passing xmltype(select value(e)
    from echoXML3,
    TABLE(xmlsequence(extract(object_value,'echoems:ECHOMetrics/OrderMetrics/OrderItemMetric/*','xmlns:echoems="http://myURL/myFilename.xsd'))) e)
    columns
    prod varchar2(20) path 'product',
    requestor varchar(50) path 'requestor'
    Message was edited by:
    user619814

Maybe you are looking for

  • I installed Firefox v. 3.6.15 on 3/21/2011. Since then Firefox crashes and closes completely when I click on certain e-mails in my inbox. How can I fix this?

    I run v. 10.6.7 Mac OS X on my iMac. Java is v. 10.6, Update 4. My Adobe reader is v. 9.4.3. Clicking on random e-mails in my inbox causes Firefox to completely close. I get a window that says "Firefox quit unexpectedly". When I click on "Reopen" I g

  • JMS Adpater Question

    I am trying to implement the JMSAdapter in the two way mode. I have configured the queues and have configured the JMS Adapter appropriately. I do see the response being generated but the correlation doesn't seem to work. Error Message: Fault ID     r

  • Configure server

    hi there, i'm currently developing my webpage using dreamweaver. however, i have to upload it to the server using a pc where dreamweaver application is not available. files with aspx extension couldnt be view. pls anyone .. help !!!

  • SDO_RELATE and 3D indexes

    Hi, The documentation I have been able to find is not very clear on this. It says that the only operator that can be used with a 3d index is SDO_FILTER. What will happen if you try and use SDO_RELATE? Will it just use SDO_FILTER? Should it return an

  • SAP HANA Web-based Development Workbench Privileges

    I can get into and use the SAP HANA web-based development workbench as the SYSTEM user, but I cannot as other users. http://localhost:8005/sap/hana/xs/ide/editor/ Currently as any other user, I get the following error: "Request execution failed due t