Help with SQL MODEL Clause

I have the privilege of performing a very tedious task.
We have some home grown regular expressions in our company. I now need to expand these regular expressions.
Samples:
a = 0-3
b = Null, 0, 1
Expression: Meaning
1:5: 1,2,3,4,5
1a: 10, 11, 12, 13
1b: 1, 10, 11
1[2,3]ab: 120, 1200, 1201, ....
It get's even more inetersting because there is a possibility of 1[2,3]a.ab
I have created two base queries to aid me in my quest. I am using the SQL MODEL clause to solve this problem. I pretty confident that I should be able to convert evrything into a range and the use one of the MODEL clause listed below.
My only confusion is how do I INCREMENT dynamically. The INCREMENT seems to be a constant in both a FOR and ITERATE statement. I need to figure a way to increment with .01, .1, etc.
Any help will be greatly appreciated.
CODE:
Reference:          http://www.sqlsnippets.com/en/topic-11663.html
Objective:          Expand a range with ITERATE
WITH t AS
(SELECT '2:4' pt
FROM DUAL
UNION ALL
SELECT '6:9' pt
FROM DUAL)
SELECT pt AS code_expression
-- , KEY
-- , min_key
-- , max_key
, m_1 AS code
FROM t
MODEL
PARTITION BY (pt)
DIMENSION BY ( 0 AS KEY )
MEASURES (
                    0 AS m_1,
                    TO_NUMBER(SUBSTR(pt, 1, INSTR(pt, ':') - 1)) AS min_key,
                    TO_NUMBER(SUBSTR(pt, INSTR(pt, ':') + 1)) AS max_key               
RULES
-- UPSERT
ITERATE (100000) UNTIL ( ITERATION_NUMBER = max_key[0] - min_key[0] )
m_1[ITERATION_NUMBER] = min_key[0] + ITERATION_NUMBER
ORDER BY pt, m_1
Explanation:
Line numbers are based on the assupmtion that "WITH t AS" starts at line 5.
If you need detailed information regarding the MODEL clause please refer to
the Refrence site stated above or read some documentation.
Partition-
Line 18:     PARTITION BY (pt)
               This will make sure that each "KEY" will start at 0 for each value of pt.
Dimension-
Line 19:     DIMENSION BY ( 0 AS KEY )     
               This is necessary for the refrences max_key[0], and min_key[0] to work.
Measures-
Line 21:      0 AS m_1
               A space holder for new values.
Line 22:     TO_NUMBER(SUBSTR(pt, 1, INSTR(pt, ':') - 1)) AS min_key
               The result is '1' for '1:5'.
Line 23:     TO_NUMBER(SUBSTR(pt, INSTR(pt, ':') + 1)) AS max_key                                        
               The result is '5' for '1:5'.
Rules-
Line 26:     UPSERT
               This makes it possible for new rows to be created.
Line 27:     ITERATE (100000) UNTIL ( ITERATION_NUMBER = max_key[0] - min_key[0] )
               This reads ITERATE 100000 times or UNTIL the ITERATION_NUMBER = max_key[0] - min_key[0]
               which would be 4 for '1:5', but since the ITERATION_NUMBER starts at 0, whatever follows
               is repaeted 5 times.
Line 29:     m_1[ITERATION_NUMBER] = min_key[0] + ITERATION_NUMBER
               m_1[ITERATION_NUMBER] means m_1[Value of Dimension KEY].
               Thus for each row of KEY the m_1 is min_key[0] + ITERATION_NUMBER.
Reference:          http://www.sqlsnippets.com/en/topic-11663.html
Objective:          Expand a range using FOR
WITH t AS
(SELECT '2:4' pt
FROM DUAL
UNION ALL
SELECT '6:9' pt
FROM DUAL)
, base AS
SELECT pt AS code_expression
, KEY AS code
, min_key
, max_key
     , my_increment
, m_1
FROM t
MODEL
PARTITION BY (pt)
DIMENSION BY ( CAST(0 AS NUMBER) AS KEY )
MEASURES (
                    CAST(NULL AS CHAR) AS m_1,
                    TO_NUMBER(SUBSTR(pt, 1, INSTR(pt, ':') - 1)) AS min_key,
                    TO_NUMBER(SUBSTR(pt, INSTR(pt, ':') + 1)) AS max_key,     
                    .1 AS my_increment     
RULES
-- UPSERT
          m_1[FOR KEY FROM min_key[0] TO max_key[0] INCREMENT 1] = 'Y'
ORDER BY pt, KEY, m_1
SELECT code_expression, code
FROM base
WHERE m_1 = 'Y'
Explanation:
Line numbers are based on the assupmtion that "WITH t AS" starts at line 5.
If you need detailed information regarding the MODEL clause please refer to
the Refrence site stated above or read some documentation.
Partition-
Line 21:     PARTITION BY (pt)
               This will make sure that each "KEY" will start at 0 for each value of pt.
Dimension-
Line 22:     DIMENSION BY ( 0 AS KEY )     
               This is necessary for the refrences max_key[0], and min_key[0] to work.
Measures-
Line 24:      CAST(NULL AS CHAR) AS m_1
               A space holder for results.
Line 25:     TO_NUMBER(SUBSTR(pt, 1, INSTR(pt, ':') - 1)) AS min_key
               The result is '1' for '1:5'.
Line 26:     TO_NUMBER(SUBSTR(pt, INSTR(pt, ':') + 1)) AS max_key                                        
               The result is '5' for '1:5'.
Line 27:     .1 AS my_increment     
               The INCREMENT I would like to use.
Rules-
Line 30:     UPSERT
               This makes it possible for new rows to be created.
               However seems like it is not necessary.
Line 32:     m_1[FOR KEY FROM min_key[0] TO max_key[0] INCREMENT 1] = 'Y'
               Where the KE value is between min_key[0] and max_key[0] set the value of m_1 to 'Y'
*/

Of course, you can accomplish the same thing without MODEL using an Integer Series Generator like this.
create table t ( min_val number, max_val number, increment_size number );
insert into t values ( 2, 3, 0.1 );
insert into t values ( 1.02, 1.08, 0.02 );
commit;
create table integer_table as
  select rownum - 1 as n from all_objects where rownum <= 100 ;
select
  min_val ,
  increment_size ,
  min_val + (increment_size * n) as val
from t, integer_table
where
  n between 0 and ((max_val - min_val)/increment_size)
order by 3
   MIN_VAL INCREMENT_SIZE        VAL
      1.02            .02       1.02
      1.02            .02       1.04
      1.02            .02       1.06
      1.02            .02       1.08
         2             .1          2
         2             .1        2.1
         2             .1        2.2
         2             .1        2.3
         2             .1        2.4
         2             .1        2.5
         2             .1        2.6
         2             .1        2.7
         2             .1        2.8
         2             .1        2.9
         2             .1          3
15 rows selected.--
Joe Fuda
http://www.sqlsnippets.com/

Similar Messages

  • Need help with SQL Query with Inline View + Group by

    Hello Gurus,
    I would really appreciate your time and effort regarding this query. I have the following data set.
    Reference_No---Check_Number---Check_Date--------Description-------------------------------Invoice_Number----------Invoice_Type---Paid_Amount-----Vendor_Number
    1234567----------11223-------------- 7/5/2008----------paid for cleaning----------------------44345563------------------I-----------------*20.00*-------------19
    1234567----------11223--------------7/5/2008-----------Adjustment for bad quality---------44345563------------------A-----------------10.00------------19
    7654321----------11223--------------7/5/2008-----------Adjustment from last billing cycle-----23543556-------------------A--------------------50.00--------------19
    4653456----------11223--------------7/5/2008-----------paid for cleaning------------------------35654765--------------------I---------------------30.00-------------19
    Please Ignore '----', added it for clarity
    I am trying to write a query to aggregate paid_amount based on Reference_No, Check_Number, Payment_Date, Invoice_Number, Invoice_Type, Vendor_Number and display description with Invoice_type 'I' when there are multiple records with the same Reference_No, Check_Number, Payment_Date, Invoice_Number, Invoice_Type, Vendor_Number. When there are no multiple records I want to display the respective Description.
    The query should return the following data set
    Reference_No---Check_Number---Check_Date--------Description-------------------------------Invoice_Number----------Invoice_Type---Paid_Amount-----Vendor_Number
    1234567----------11223-------------- 7/5/2008----------paid for cleaning----------------------44345563------------------I-----------------*10.00*------------19
    7654321----------11223--------------7/5/2008-----------Adjustment from last billing cycle-----23543556-------------------A--------------------50.00--------------19
    4653456----------11223--------------7/5/2008-----------paid for cleaning------------------------35654765-------------------I---------------------30.00--------------19
    The following is my query. I am kind of lost.
    select B.Description, A.sequence_id,A.check_date, A.check_number, A.invoice_number, A.amount, A.vendor_number
    from (
    select sequence_id,check_date, check_number, invoice_number, sum(paid_amount) amount, vendor_number
    from INVOICE
    group by sequence_id,check_date, check_number, invoice_number, vendor_number
    ) A, INVOICE B
    where A.sequence_id = B.sequence_id
    Thanks,
    Nick

    It looks like it is a duplicate thread - correct me if i'm wrong in this case ->
    Need help with SQL Query with Inline View + Group by
    Regards.
    Satyaki De.

  • Where clause "where 1=1" help with SQL tuning

    Hello Tuning experts,
    Is it helpful to use "where 1=1" and then put all the joins and conditions in the "AND" statements of the SQL when writing SQL queries. I would like to know if it helps with query performance to write SQL queirs that way.
    Thanks in advance.
    Edited by: oracle_developer on Oct 8, 2012 10:41 AM

    You can see here that "where 1 = 1" is gone from the predicate info in the explain plan.
    The optimizer simply discarded it.
    SQL> explain plan for
      2  select *
      3  from emp
      4  where 1 = 1
      5  and job = 'SALESMAN';
    Explained.
    PLAN_TABLE_OUTPUT
    Plan hash value: 3956160932
    | Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT  |      |     3 |   114 |     3   (0)| 00:00:01 |
    |*  1 |  TABLE ACCESS FULL| EMP  |     3 |   114 |     3   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       1 - filter("JOB"='SALESMAN')
    13 rows selected.

  • Need help with SQL*Loader not working

    Hi all,
    I am trying to run SQL*Loader on Oracle 10g UNIX platform (Red Hat Linux) with below command:
    sqlldr userid='ldm/password' control=issue.ctl bad=issue.bad discard=issue.txt direct=true log=issue.log
    And get below errors:
    SQL*Loader-128: unable to begin a session
    ORA-01034: ORACLE not available
    ORA-27101: shared memory realm does not exist
    Linux-x86_64 Error: 2: No such file or directory
    Can anyone help me out with this problem that I am having with SQL*Loader? Thanks!
    Ben Prusinski

    Hi Frank,
    More progress, I exported the ORACLE_SID and tried again but now have new errors! We are trying to load an Excel CSV file into a new table on our Oracle 10g database. I created the new table in Oracle and loaded with SQL*Loader with below problems.
    $ export ORACLE_SID=PROD
    $ sqlldr 'ldm/password@PROD' control=prod.ctl log=issue.log bad=bad.log discard=discard.log
    SQL*Loader: Release 10.2.0.1.0 - Production on Tue May 23 11:04:28 2006
    Copyright (c) 1982, 2005, Oracle. All rights reserved.
    SQL*Loader: Release 10.2.0.1.0 - Production on Tue May 23 11:04:28 2006
    Copyright (c) 1982, 2005, Oracle. All rights reserved.
    Control File: prod.ctl
    Data File: prod.csv
    Bad File: bad.log
    Discard File: discard.log
    (Allow all discards)
    Number to load: ALL
    Number to skip: 0
    Errors allowed: 50
    Bind array: 64 rows, maximum of 256000 bytes
    Continuation: none specified
    Path used: Conventional
    Table TESTLD, loaded from every logical record.
    Insert option in effect for this table: REPLACE
    Column Name Position Len Term Encl Datatype
    ISSUE_KEY FIRST * , CHARACTER
    TIME_DIM_KEY NEXT * , CHARACTER
    PRODUCT_CATEGORY_KEY NEXT * , CHARACTER
    PRODUCT_KEY NEXT * , CHARACTER
    SALES_CHANNEL_DIM_KEY NEXT * , CHARACTER
    TIME_OF_DAY_DIM_KEY NEXT * , CHARACTER
    ACCOUNT_DIM_KEY NEXT * , CHARACTER
    ESN_KEY NEXT * , CHARACTER
    DISCOUNT_DIM_KEY NEXT * , CHARACTER
    INVOICE_NUMBER NEXT * , CHARACTER
    ISSUE_QTY NEXT * , CHARACTER
    GROSS_PRICE NEXT * , CHARACTER
    DISCOUNT_AMT NEXT * , CHARACTER
    NET_PRICE NEXT * , CHARACTER
    COST NEXT * , CHARACTER
    SALES_GEOGRAPHY_DIM_KEY NEXT * , CHARACTER
    value used for ROWS parameter changed from 64 to 62
    Record 1: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 2: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 3: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 4: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 5: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 6: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 7: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 8: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 9: Rejected - Error on table ISSUE_FACT_TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 10: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 11: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 12: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 13: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 14: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 15: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 16: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 17: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 18: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 19: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 20: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 21: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 22: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 23: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 24: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    Record 39: Rejected - Error on table TESTLD, column DISCOUNT_AMT.
    Column not found before end of logical record (use TRAILING NULLCOLS)
    MAXIMUM ERROR COUNT EXCEEDED - Above statistics reflect partial run.
    Table TESTLD:
    0 Rows successfully loaded.
    51 Rows not loaded due to data errors.
    0 Rows not loaded because all WHEN clauses were failed.
    0 Rows not loaded because all fields were null.
    Space allocated for bind array: 255936 bytes(62 rows)
    Read buffer bytes: 1048576
    Total logical records skipped: 0
    Total logical records read: 51
    Total logical records rejected: 51
    Total logical records discarded: 0
    Run began on Tue May 23 11:04:28 2006
    Run ended on Tue May 23 11:04:28 2006
    Elapsed time was: 00:00:00.14
    CPU time was: 00:00:00.01
    [oracle@casanbdb11 sql_loader]$
    Here is the control file:
    LOAD DATA
    INFILE issue_fact.csv
    REPLACE
    INTO TABLE TESTLD
    FIELDS TERMINATED BY ','
    ISSUE_KEY,
    TIME_DIM_KEY,
    PRODUCT_CATEGORY_KEY,
    PRODUCT_KEY,
    SALES_CHANNEL_DIM_KEY,
    TIME_OF_DAY_DIM_KEY,
    ACCOUNT_DIM_KEY,
    ESN_KEY,
    DISCOUNT_DIM_KEY,
    INVOICE_NUMBER,
    ISSUE_QTY,
    GROSS_PRICE,
    DISCOUNT_AMT,
    NET_PRICE,
    COST,
    SALES_GEOGRAPHY_DIM_KEY
    )

  • Help with logical model

    Hi, I am new to this software and need some help with a simple logical model.
    Here is the task:
    I need to create a model for a parking garage.
    Each level can have any number of lots.
    There are different types of lots (handicapped, women, regular, ...) with different Prices and Sizes.
    It is important for the users and the system to know whether a lot is free or occupied.
    It is crucial to assign numbers to the lots, so users can find it again.
    And this is my model:
    Level 1:n Lot n:1 Type
    (#Level) (#Number,*Availability) (#Type,*Price,*Size)
    Question:
    Is it correct or would you change something? I am not quite sure whether to make availability and level an entity or an attribute of Lot.
    Which data types do I need to assign each attribute? What is the difference between logical and domain?
    Thanks in advance
    Edited by: user13256814 on Jun 2, 2010 3:51 AM

    Hi Bhaskaran,
      u can see the logs correspoding to your application in the server location..
    \usr\sap\<sid>\<instance_number>\j2ee\cluster\server0\
    i think ur application folder will be there inside this or within one subdirectory here.
    http://help.sap.com/saphelp_nw04s/helpdata/en/fe/4f5542253fb330e10000000a155106/content.htm
    U can check the service entries in services file which is located in
    <Drive Name>:\WINDOWS\system32\drivers\etc...
    but normally in JCO Connection test , if it is not showing errors(especially MetaData) , then it means this entry is there in the services file.
                                   Regards
                                     Kishor Gopinathan

  • XSQL Using bind params with sql LIKE clause

    I am unable to use a bind-param with the LIKE clause in a SELECT statement.
    eg call .../temp.xsql?name=N
    XSQL query is this:
    <xsql:query max-rows="-1" bind-params="name">
    SELECT last_name
    FROM emp
    WHERE last_name LIKE '?%'
    </xsql:query>
    I have tried a few combinations so far with no success eg:
    WHERE last_name LIKE '{@name}%'
    WHERE last_name LIKE ?||%
    Any ideas?

    I highly recommend using XSQL's real bind variable feature wherever you can. You can read about it in the XSQL Online Documentation (Search for the "Using Bind Variables" section).
    Using this feature is more performant and more secure than using textual substitution variables.
    Here's what your page looks like using textual substitution:
    <page connection="UTD4" xmlns:xsql="urn:oracle-xsql">
      <xsql:query null-indicator="yes" >
        SELECT * FROM TC_HL7_SEG WHERE SEGMENT_CODE LIKE '{@code}%'
      </xsql:query>
    </page> .
    And here's what it would look like using real bind variables:
    <page connection="UTD4" xmlns:xsql="urn:oracle-xsql">
      <xsql:query null-indicator="yes" bind-params="code">
        SELECT * FROM TC_HL7_SEG WHERE SEGMENT_CODE LIKE ?||'%'
      </xsql:query>
    </page> .
    Using real bind variables allows the database to avoid reparsing the SQL statement everytime, which improves performance.
    Steve Muench
    JDeveloper/BC4J Development Team
    Author, Building Oracle XML Applications

  • Where to find help with SQL Developer installation?

    Hi,
    I just want to try out SQL Developer and compare its capabilities to TOAD's. Unfortunately, I am not PC software savvy and now am stuck with a SQL Developer (sqldeveloper-1.2.2998) installation problem. When I clicked on the .exe file, I got a blank SQL Developer screen - there is nothing in the screen except a heading that reads 'Oracle SQL Developer'...
    Does anyone know of a blog or a site that I can get some help with problems like mine?
    Any help is much appreciated!

    Hi,
    SQL Developer forum link:
    "http://forums.oracle.com/forums/forum.jspa?forumID=260"
    There are 2 versions of SQL Developer, with/without JRE.
    Try out the full install version with JRE.
    HTH
    Zack

  • Need help with ORDER BY clause

    Hey,
    I have a table:
    Name: Year:
    Eagle 2000
    Tiger 2001
    Eagle 2002
    Lion 2006
    Lion 1999
    Fox 1991
    Lion 1995
    I need a query which will return in such order:
    Name: Year: Position:
    Eagle 2000 1
    Eagle 2002 2
    Fox 1991 1
    Lion 1995 1
    Lion 1999 2
    Lion 2006 3
    Tiger 2001 1
    So, of course to get Name and Year in this order is quite easy:
    select Name, Year from Animals order by Name, Year;
    but how about Position, is there a way to count it with SQL?
    any help is welcome,
    Silvestras

    SQL> with rt as
      2  (select 'Eagle' nm, 2000 yr from dual union all
      3  select 'Tiger', 2001 from dual union all
      4  select 'eagle', 2002 from dual union all
      5  select 'Lion', 2006 from dual union all
      6  select 'Lion', 1999 from dual union all
      7  select 'Fox', 1991 from dual union all
      8  select 'Lion', 1995 from dual)
      9  select nm,yr,row_number() over(partition by (nm) order by nm,yr) position from rt;
    NM            YR   POSITION
    Eagle       2000          1
    Fox         1991          1
    Lion        1995          1
    Lion        1999          2
    Lion        2006          3
    Tiger       2001          1
    eagle 2002 1
    7 rows selected.
    SQL> with rt as
      2  (select 'Eagle' nm, 2000 yr from dual union all
      3  select 'Tiger', 2001 from dual union all
      4  select 'eagle', 2002 from dual union all
      5  select 'Lion', 2006 from dual union all
      6  select 'Lion', 1999 from dual union all
      7  select 'Fox', 1991 from dual union all
      8  select 'Lion', 1995 from dual)
      9  select nm,yr,row_number() over(partition by lower(nm) order by nm,yr) position from rt;
    NM            YR   POSITION
    Eagle       2000          1
    eagle 2002 2
    Fox         1991          1
    Lion        1995          1
    Lion        1999          2
    Lion        2006          3
    Tiger       2001          1
    7 rows selected.
    SQL> 

  • Please help with SQL amount calulation

    -- Results
    with t as ( 
    select 'P11877' Mstr_Program,   1 Year_of_study, 'BUSI1490' program_module,  20 no_of_stud,    1 rank,   30 program_credits,  30 cumm_credits   from dual union all
    select 'P11877',                1,              'COMP1365',                 20,               2,        30,                  60               from dual union all
    select 'P11877',                1,              'BUSI1375',                 20,               3,        30,                  90               from dual union all
    select 'P11877',                1,              'COMP1363',                 20,               4,        30,                  120              from dual union all
    select 'P11877',                2,              'MARK1174',                 8,                1,        30,                  30               from dual union all
    select 'P11877',                2,              'FINA1068',                 8,                2,        15,                  45               from dual union all
    select 'P11877',                2,              'INDU1062',                 8,                3,        30,                  75               from dual union all
    select 'P11877',                2,              'BUSI1329',                 8,                4,        15,                  90               from dual union all
    select 'P11877',                2,              'MARK1138',                 8,                5,        30,                  120              from dual)
    select * from t;-- Each MSTR_PROGRAM can have 1 or many program_module
    -- MSTR_PROGRAM's can run for 1 or 2 years (case above is two years) so some modules run in year 1 and some in year 2
    -- NO_OF_STUD is the number of students on the module
    -- RANK basically ranks the modules by the number of students on them grouped by program and year
    -- e.g.row_number() OVER (PARTITION BY Mstr_Program, Year_of_study) ORDER BY COUNT(STUDENT_ID) DESC) rank
    -- PROGRAM_CREDITS: each module has a fixed number of credits
    -- CUMM_CREDITS: Increments the credit count of modules
    -- SUM(program_credits * 10) OVER (PARTITION BY Mstr_Program, Year_of_study
    -- ORDER BY count(STUDENT_ID) desc ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) cumm_credits
    -- I want to trim of any modules once the CUM_CREDITS hits 120. As seen above. I achieve this by wrapping the main query is another SELECT then LIMIT
    -- that WHERE cum_credit <=120.
    -- But what I need is:
    -- In some cases the the cumm_credit maybe on lets say 90credits then the next module is worth 40 credits. This next module will not show as it
    -- will be greater than 120 credits, so i need to pro-rata it:
    -- So if credit_count > 120, then the last module is counted pro-rata as follows: 1- ((credit count - 120) / credits from last module
    -- Can anyone help with how I can incorporate this into my current code: The SELECT portion of the Original SQL is below: I simplified column names
    -- e.t.c in the above so they wont be the same
    SELECT * FROM (
         SELECT
               ,SR_PROGRAM Mstr_Program
               ,DECODE (SORLCUR_YEAR, 1, 1,
                                      2, 2,
                                      3, 3,
                                      4, 3, SR_YEAR) year_of_study
               ,SCT_SUBJ_CODE||SCT_CRSE_NUMB program_module
               ,COUNT(student_ID)                    no_of_stud
               ,row_number() OVER (PARTITION BY sr_program,
                                            DECODE (sr_year, 1, 1,
                                                                  2, 2,
                                                                  3, 3,
                                                                  4, 3, SR_YEAR) ORDER BY COUNT(student_id) DESC, scbcrse_title asc) rank
               ,(SCT_CREDIT_HRS * 10) program_credits
               ,SUM(SCT_CREDIT_HRS * 10) OVER (PARTITION BY sr_program, DECODE (sorlcur_year, 1, 1,
                                                                                                       2, 2,
                                                                                                       3, 3,
                                                                                                       4, 3, SR_YEAR)
                                                    ORDER BY count(student_id) desc ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) cumm_credits
    WHERE cumm_credit <=120
    ORDER BY Mstr_Program, YEAR_OF_STUDY, RANK asc;

    Maybe
    SELECT Mstr_Program,year_of_study,program_module,no_of_stud,rank,program_credits old_program_credits,cumm_credits old_cumm_credits,
           case when cumm_credits > 120
                then program_credits - cumm_credits + 120
                else program_credits
           end new_program_credits,
           case when cumm_credits > 120
                then 120
                else cumm_credits
           end new_cumm_credits
      FROM (SELECT SR_PROGRAM Mstr_Program,
                   DECODE(SORLCUR_YEAR,1,1,2,2,3,3,4,3,SR_YEAR) year_of_study,
                   SCT_SUBJ_CODE||SCT_CRSE_NUMB program_module,
                   COUNT(student_ID) no_of_stud,
                   row_number() OVER (PARTITION BY sr_program,DECODE(sr_year,1,1,2,2,3,3,4,3,SR_YEAR)
                                          ORDER BY COUNT(student_id) DESC,scbcrse_title) rank,
                   10 * SCT_CREDIT_HRS program_credits,
                   10 * SUM(SCT_CREDIT_HRS) OVER (PARTITION BY sr_program,DECODE(sorlcur_year,1,1,2,2,3,3,4,3,SR_YEAR)
                                                      ORDER BY count(student_id) desc
                                                  ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) cumm_credits
    WHERE 0 <= case when cumm_credits > 120
                     then program_credits - cumm_credits + 120
                     else program_credits
                end
    ORDER BY Mstr_Program,YEAR_OF_STUDY,RANKRegards
    Etbin
    Edited by: Etbin on 16.12.2011 8:50
    with
    t as   /* simulating the result achieved */
    (select 'P11877' Mstr_Program,1 Year_of_study, 'BUSI1490' program_module,20 no_of_stud,1 rank,30 program_credits,30 cumm_credits from dual union all
    select 'P11877',             1,               'COMP1365',               20,           2,     40,                70              from dual union all
    select 'P11877',             1,               'BUSI1375',               20,           3,     30,                100             from dual union all
    select 'P11877',             1,               'COMP1363',               20,           4,     40,                140             from dual union all
    select 'P11877',             2,               'MARK1174',               8,            1,     30,                30              from dual union all
    select 'P11877',             2,               'FINA1068',               8,            2,     50,                80              from dual union all
    select 'P11877',             2,               'INDU1062',               8,            3,     30,                110             from dual union all
    select 'P11877',             2,               'BUSI1329',               8,            4,     50,                160             from dual union all
    select 'P11877',             2,               'MARK1138',               8,            5,     30,                190             from dual
    select Mstr_Program,Year_of_study,program_module,no_of_stud,rank,program_credits old_credits,cumm_credits old_cumm,
           case when cumm_credits > 120
                then program_credits - cumm_credits + 120
                else program_credits
           end new_program_credits,
           case when cumm_credits > 120
                then 120
                else cumm_credits
           end new_cumm_credits
      from t
    where 0 <= case when cumm_credits > 120
                     then program_credits - cumm_credits + 120
                     else program_credits
                end

  • Help with SQL Server 2005 http Endpoint

    I am trying to use mx:webservice to directly connect to a SQL
    Server 2005 HTTP Endpoint. Is this possible. Is there going to be a
    problem with crossdomain issues? If the Endpoint is actively
    listening on port 80 then IIS cannot. So I cannot place
    crossdomain.xml in webserver, how will I overcome this crossdomain
    problem? Am I making this more complicated than it is? If anyone
    has an example it would be appreciated. All I want is a flex2 app
    talking directly to sql server. Seems possible.

    Kent, I see that many others have reported that error (doing
    a google search), but I see no ready answers. I saw something that
    reminded me of a connection string value that I've seen answer some
    problems. May be worth a shot for you: try adding this string to
    the connection string (in "advanced options") for your datasource:
    AuthenticationMethod=Type2
    If it doesn't solve it, remove it. But keep it handy in case
    it ever may help with some other problem.
    Here's one other possible answer for you:
    http://www.webmasterkb.com/Uwe/Forum.aspx/coldfusion-server/3206/SQL-Server-2000-Windows-A uth
    Sorry I can't be more clear for you.

  • I need help with SQL query

    Hi All,
    I have a problem in the query below. When I run the query I got a pop-up screen to ente value for
    :total_balance,
    :emp_code,
    :from_date,
    :to_date
    total_balance supose to be a result of a calculation.
    Your assistance is apreciated. Thanks,
    Ribhi
    select      FK_VOUCHERSERIAL_N,
         FK_VOUCHERVALUE_DA,
         DESCRIPTION,
         nvl(AMOUNT,0) amount,
         TYPE,
         Accnt101.postive_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) postive_amount,
         Accnt101.negative_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) negative_amount,
         Accnt101.total_balanceformula(:total_balance, EMPLOYEE_TRANSACTI.TYPE,Accnt101.negative_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) ,Accnt101.postive_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) , nvl(AMOUNT,0)) total_balance
    from      EMPLOYEE_TRANSACTI
    where     FK_EMPLOYEENUMBER0=:emp_code
    and     STATUS=1
    and     FK_VOUCHERVALUE_DA<=:to_date
    and     FK_VOUCHERVALUE_DA>=:from_date
    and     ((TYPE >7 and TYPE <16)
         or (TYPE >34 and TYPE <43)
         or (TYPE =7)
         or (TYPE =18)
         or (TYPE >26 and TYPE <35)
         or (TYPE =17)
         OR (TYPE = 60)
         OR (TYPE = 70)
    OR (TYPE = 72)
    OR (TYPE = 73)
    OR (TYPE = 74)
         or (type = 21)
         or (type =24)
         or (type = 81)
         or (type = 82))
    order by      FK_VOUCHERVALUE_DA asc, FK_VOUCHERSERIAL_N asc, type desc

    Hi Satyaki,
    My problem is with SQL and PL/SQL codd. I managed to convert some of my reports and now I'm facing a problem with converted SQL and PL/SQL code. To give you an Idea the following is a sample of a converted report.
    Pls have a look. (p.s how can i post formated text)
    Thanks,
    Ribhi
    1 - XML template file
    <?xml version="1.0" encoding="UTF-8" ?>
    - <dataTemplate name="Accnt101" defaultPackage="Accnt101" version="1.0">
    - <properties>
    <property name="xml_tag_case" value="upper" />
    </properties>
    - <parameters>
    <parameter name="FROM_DATE" dataType="date" defaultValue="01/01/1998" />
    <parameter name="TO_DATE" dataType="date" defaultValue="31/12/1998" />
    <parameter name="EMP_CODE" dataType="number" defaultValue="44" />
    </parameters>
    <lexicals />
    - <dataQuery>
    - <sqlStatement name="employee_trans">
    - <![CDATA[
    select      FK_VOUCHERSERIAL_N,
         FK_VOUCHERVALUE_DA,
         DESCRIPTION,
         nvl(AMOUNT,0) amount,
         TYPE,
         Accnt101.postive_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) postive_amount,
         Accnt101.negative_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) negative_amount,
         Accnt101.total_balanceformula(:total_balance, EMPLOYEE_TRANSACTI.TYPE,Accnt101.negative_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) ,Accnt101.postive_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) , nvl(AMOUNT,0)) total_balance
    from      EMPLOYEE_TRANSACTI
    where     FK_EMPLOYEENUMBER0=:emp_code
    and     STATUS=1
    and     FK_VOUCHERVALUE_DA<=:to_date
    and     FK_VOUCHERVALUE_DA>=:from_date
    and     ((TYPE >7 and TYPE <16)
         or (TYPE >34 and TYPE <43)
         or (TYPE =7)
         or (TYPE =18)
         or (TYPE >26 and TYPE <35)
         or (TYPE =17)
         OR (TYPE = 60)
         OR (TYPE = 70)
                    OR (TYPE = 72)
                    OR (TYPE = 73)
                    OR (TYPE = 74)
         or (type = 21)
         or (type =24)
         or (type = 81)
         or (type = 82))
    order by      FK_VOUCHERVALUE_DA asc, FK_VOUCHERSERIAL_N asc, type desc
      ]]>
    </sqlStatement>
    - <sqlStatement name="employee">
    - <![CDATA[
    select NAME,NUMBER0
    from EMPLOYEE
    where  NUMBER0=:emp_code
      ]]>
    </sqlStatement>
    </dataQuery>
    <dataTrigger name="beforeReportTrigger" source="Accnt101.beforereport" />
    - <dataStructure>
    - <group name="G_employee_trans" dataType="varchar2" source="employee_trans">
    <element name="FK_VOUCHERSERIAL_N" dataType="number" value="FK_VOUCHERSERIAL_N" />
    <element name="FK_VOUCHERVALUE_DA" dataType="date" value="FK_VOUCHERVALUE_DA" />
    <element name="DESCRIPTION" dataType="varchar2" value="DESCRIPTION" />
    <element name="AMOUNT" dataType="number" value="AMOUNT" />
    <element name="postive_amount" dataType="number" value="postive_amount" />
    <element name="negative_amount" dataType="number" value="negative_amount" />
    <element name="total_balance" dataType="number" value="total_balance" />
    <element name="TYPE" dataType="number" value="TYPE" />
    <element name="CS_1" function="sum" dataType="number" value="G_employee_trans.total_balance" />
    </group>
    - <group name="G_employee" dataType="varchar2" source="employee">
    <element name="NUMBER0" dataType="number" value="NUMBER0" />
    <element name="NAME" dataType="varchar2" value="NAME" />
    </group>
    <element name="balance" dataType="number" value="Accnt101.balance_p" />
    <element name="CS_2" function="count" dataType="number" value="G_employee.NUMBER0" />
    <element name="CS_3" function="count" dataType="number" value="G_employee_trans.AMOUNT" />
    </dataStructure>
    </dataTemplate>
    2 - PLS/SQL package
    CREATE OR REPLACE PACKAGE Accnt101 AS
         from_date     date;
         to_date     date;
         emp_code     number;
         balance     number := 0 ;
         function postive_amountformula(TYPE in number, amount in number) return number ;
         function negative_amountformula(TYPE in number, amount in number) return number ;
         function BeforeReport return boolean ;
         function total_balanceformula(total_balance in number, TYPE in number, negative_amount in number, postive_amount in number, amount in number) return number ;
         Function balance_p return number;
    END Accnt101;
    3- Package Body
    CREATE OR REPLACE PACKAGE BODY Accnt101 AS
    function postive_amountformula(TYPE in number, amount in number) return number is
    begin
         if ((TYPE>26 and TYPE<35)
              or (TYPE=17))
         then
              return(amount);
         elsif (type = 70)and (amount >=0) then
              return (amount) ;
    elsif (type = 72)and (amount >=0) then
              return (amount) ;
    elsif (type = 73)and (amount >=0) then
              return (amount) ;
    elsif (type = 74)and (amount >=0) then
              return (amount) ;
         elsif (type = 60)and (amount >=0) then
              return (amount) ;
         else
              return (null) ;
         end if;
    RETURN NULL; end;
    function negative_amountformula(TYPE in number, amount in number) return number is
    begin
         if ((TYPE>7 and TYPE<16)
              or (TYPE >34 and TYPE <43)
              or (TYPE=7)
              or (TYPE=18)
              or (type=21)
              or (type=24)
              or (type= 81)
              or (type=82))
         then
              return(amount);
         elsif (type = 70)and (amount <0) then
              return (abs (amount)) ;
    elsif (type = 72)and (amount <0) then
              return (abs (amount)) ;
    elsif (type = 73)and (amount <0) then
              return (abs (amount)) ;
    elsif (type = 74)and (amount <0) then
              return (abs (amount)) ;
         elsif (type = 60)and (amount <0) then
              return (abs(amount)) ;
         else
              return (null) ;
         end if;
    RETURN NULL; end;
    function BeforeReport return boolean is
    var_pos     number(15,3) ;
    var_neg     number(15,3) ;
    beg_bal     number(15,3) ;
    Begin
    begin
    select sum (nvl(amount,0)) into beg_bal
         from EMPLOYEE_TRANSACTI
         where (TYPE=99 or type = 92 or type = 93 or type = 94)
         and to_char(from_date,'YYYY')=to_char(date0,'YYYY')
         and FK_EMPLOYEENUMBER0=emp_code;
    EXCEPTION
         WHEN NO_DATA_FOUND THEN
         beg_bal := 0;
    end;
    begin
         select      sum(nvl(amount,0)) into var_pos
         from      EMPLOYEE_TRANSACTI
         where      
              (TYPE=17
              or type=60
              OR TYPE=70
    oR TYPE=72
    OR TYPE=73
    OR TYPE=74
              or (TYPE>26 and TYPE<35))
         and      fk_vouchervalue_da<from_date
         and      fk_vouchervalue_da>= trunc(from_date,'year')
         and      FK_EMPLOYEENUMBER0=emp_code;
    EXCEPTION
         WHEN NO_DATA_FOUND THEN
         var_pos := 0;
    end;
    Begin     
         select sum(nvl(amount,0)) into var_neg
         from EMPLOYEE_TRANSACTI
         where ((TYPE>7 and TYPE<16)
              or (TYPE >34 and TYPE <43)
              or (TYPE=7)
              or (TYPE=18)
              or (type=21)
              or (type=24)
              or (type= 81)
              or (type=82) )
         and fk_vouchervalue_da<from_date
         and fk_vouchervalue_da>= trunc(from_date,'year')
         and FK_EMPLOYEENUMBER0=emp_code;
         balance :=nvl(beg_bal,0) + nvl(var_pos,0) - nvl(var_neg,0);
         return(true);
    EXCEPTION
         WHEN NO_DATA_FOUND THEN
         balance :=nvl(beg_bal,0) + nvl(var_pos,0) - nvl(var_neg,0);
              RETURN (TRUE);
    end;
    RETURN NULL; end;
    function total_balanceformula(total_balance in number, TYPE in number, negative_amount in number, postive_amount in number, amount in number) return number is
    begin
         if total_balance is null then
         if ((TYPE>7 and TYPE<16)
              or (TYPE >34 and TYPE <43)
              or (TYPE=7)or (TYPE=18)
              or (type=21) or (type=24)
              or (type= 81)
              or (type=82))
         then
              return(balance-negative_amount);
         elsif ((TYPE>26 and TYPE<35) or (TYPE=17))
              then
                   return(balance+postive_amount);
              elsif (type=70 or type=72 or type=73 or type=74
    or type=60) and (amount >=0) then
                   return(balance+postive_amount);
              elsif (type=70 or type=72 or type=73 or type=74
    or type=60) and (amount <0) then
                   return(balance-negative_amount);
         end if;
         else
         if ((TYPE>7 and TYPE<16)
              or (TYPE >34 and TYPE <43)
              or (TYPE=7)or (TYPE=18)
              or (type=21) or (type=24)
              or (type= 81)
              or (type=82))
         then
              return(total_balance-negative_amount);
         elsif ((TYPE>26 and TYPE<35) or (TYPE=17))
              then
                   return(total_balance+postive_amount);
              elsif (type=70 or type=72 or type=73 or type=74
    or type=60) and (amount >=0) then
                   return(total_balance+postive_amount);
              elsif (type=70 or type=72 or type=73 or type=74
    or type=60) and (amount <0) then
                   return(total_balance-negative_amount);
         end if;
         end if ;
    RETURN NULL; end;
    Functions to refer Oracle report placeholders
    Function balance_p return number is
         Begin
         return balance;
         END;
    END Accnt101 ;

  • SQL-Model-Clause / Example 2    in  Data Warehousing Guide   11G/Chapter 24

    Hi SQL-Experts
    I have a RH 5.7/Oracle 11.2-Environment!
    The sample schemas are installed!
    I executed as in Example 2 in Data Warehousing Guide 11G/Chapter 24:
    CREATE TABLE currency (
       country         VARCHAR2(20),
       year            NUMBER,
       month           NUMBER,
       to_us           NUMBER);
    INSERT INTO currency
    (SELECT distinct
    SUBSTR(country_name,1,20), calendar_year, calendar_month_number, 1
    FROM countries
    CROSS JOIN times t
    WHERE calendar_year IN (2000,2001,2002)
    UPDATE currency set to_us=.74 WHERE country='Canada';and then:
    WITH  prod_sales_mo AS       --Product sales per month for one country
    SELECT country_name c, prod_id p, calendar_year  y,
       calendar_month_number  m, SUM(amount_sold) s
    FROM sales s, customers c, times t, countries cn, promotions p, channels ch
    WHERE  s.promo_id = p.promo_id AND p.promo_total_id = 1 AND
           s.channel_id = ch.channel_id AND ch.channel_total_id = 1 AND
           s.cust_id=c.cust_id  AND
           c.country_id=cn.country_id AND country_name='France' AND
           s.time_id=t.time_id  AND t.calendar_year IN  (2000, 2001,2002)
    GROUP BY cn.country_name, prod_id, calendar_year, calendar_month_number
                        -- Time data used for ensuring that model has all dates
    time_summary AS(  SELECT DISTINCT calendar_year cal_y, calendar_month_number cal_m
      FROM times
      WHERE  calendar_year IN  (2000, 2001, 2002)
                       --START: main query block
    SELECT c, p, y, m, s,  nr FROM (
    SELECT c, p, y, m, s,  nr
    FROM prod_sales_mo s
                       --Use partition outer join to make sure that each combination
                       --of country and product has rows for all month values
      PARTITION BY (s.c, s.p)
         RIGHT OUTER JOIN time_summary ts ON
            (s.m = ts.cal_m
             AND s.y = ts.cal_y
    MODEL
      REFERENCE curr_conversion ON
          (SELECT country, year, month, to_us
          FROM currency)
          DIMENSION BY (country, year y,month m) MEASURES (to_us)
                                    --START: main model
       PARTITION BY (s.c c)
       DIMENSION BY (s.p p, ts.cal_y y, ts.cal_m m)
       MEASURES (s.s s, CAST(NULL AS NUMBER) nr,
                 s.c cc ) --country is used for currency conversion
       RULES (
                          --first rule fills in missing data with average values
          nr[ANY, ANY, ANY]
             = CASE WHEN s[CV(), CV(), CV()] IS NOT NULL
                  THEN s[CV(), CV(), CV()]
                  ELSE ROUND(AVG(s)[CV(), CV(), m BETWEEN 1 AND 12],2)
               END,
                          --second rule calculates projected values for 2002
          nr[ANY, 2002, ANY] = ROUND(
             ((nr[CV(),2001,CV()] - nr[CV(),2000, CV()])
              / nr[CV(),2000, CV()]) * nr[CV(),2001, CV()]
             + nr[CV(),2001, CV()],2),
                          --third rule converts 2002 projections to US dollars
          nr[ANY,y != 2002,ANY]
             = ROUND(nr[CV(),CV(),CV()]
               * curr_conversion.to_us[ cc[CV(),CV(),CV()], CV(y), CV(m)], 2)
    ORDER BY c, p, y, m)
    WHERE y = '2002'
    ORDER BY c, p, y, m;I got the following error:
    ORA-00947: not enough values
    00947. 00000 -  "not enough values"
    *Cause:   
    *Action:
    Error at Line: 39 Column: 83But when I changed the part
    curr_conversion.to_us[ cc[CV(),CV(),CV()], CV(y), CV(m)], 2) of 3.rd Rules to
    curr_conversion.to_us[ cc[CV(),CV(),CV()] || '', CV(y), CV(m)], 2)or
    curr_conversion.to_us[ cc[CV(),CV(),CV()] || null, CV(y), CV(m)], 2)It worked!
    My questions:
    1/Can anyone explain me why it worked and why it didn't work?
    2/Rule 3 has not the same meaning as the comment, Is it an error? Or I misunderstood anything?
    the comment is: third rule converts 2002 projections to US dollars the left side has y != 2002 Thank for any help !
    regards
    hqt200475
    Edited by: hqt200475 on Dec 20, 2012 4:45 AM

    Hi SQL-Experts
    I have a RH 5.7/Oracle 11.2-Environment!
    The sample schemas are installed!
    I executed as in Example 2 in Data Warehousing Guide 11G/Chapter 24:
    CREATE TABLE currency (
       country         VARCHAR2(20),
       year            NUMBER,
       month           NUMBER,
       to_us           NUMBER);
    INSERT INTO currency
    (SELECT distinct
    SUBSTR(country_name,1,20), calendar_year, calendar_month_number, 1
    FROM countries
    CROSS JOIN times t
    WHERE calendar_year IN (2000,2001,2002)
    UPDATE currency set to_us=.74 WHERE country='Canada';and then:
    WITH  prod_sales_mo AS       --Product sales per month for one country
    SELECT country_name c, prod_id p, calendar_year  y,
       calendar_month_number  m, SUM(amount_sold) s
    FROM sales s, customers c, times t, countries cn, promotions p, channels ch
    WHERE  s.promo_id = p.promo_id AND p.promo_total_id = 1 AND
           s.channel_id = ch.channel_id AND ch.channel_total_id = 1 AND
           s.cust_id=c.cust_id  AND
           c.country_id=cn.country_id AND country_name='France' AND
           s.time_id=t.time_id  AND t.calendar_year IN  (2000, 2001,2002)
    GROUP BY cn.country_name, prod_id, calendar_year, calendar_month_number
                        -- Time data used for ensuring that model has all dates
    time_summary AS(  SELECT DISTINCT calendar_year cal_y, calendar_month_number cal_m
      FROM times
      WHERE  calendar_year IN  (2000, 2001, 2002)
                       --START: main query block
    SELECT c, p, y, m, s,  nr FROM (
    SELECT c, p, y, m, s,  nr
    FROM prod_sales_mo s
                       --Use partition outer join to make sure that each combination
                       --of country and product has rows for all month values
      PARTITION BY (s.c, s.p)
         RIGHT OUTER JOIN time_summary ts ON
            (s.m = ts.cal_m
             AND s.y = ts.cal_y
    MODEL
      REFERENCE curr_conversion ON
          (SELECT country, year, month, to_us
          FROM currency)
          DIMENSION BY (country, year y,month m) MEASURES (to_us)
                                    --START: main model
       PARTITION BY (s.c c)
       DIMENSION BY (s.p p, ts.cal_y y, ts.cal_m m)
       MEASURES (s.s s, CAST(NULL AS NUMBER) nr,
                 s.c cc ) --country is used for currency conversion
       RULES (
                          --first rule fills in missing data with average values
          nr[ANY, ANY, ANY]
             = CASE WHEN s[CV(), CV(), CV()] IS NOT NULL
                  THEN s[CV(), CV(), CV()]
                  ELSE ROUND(AVG(s)[CV(), CV(), m BETWEEN 1 AND 12],2)
               END,
                          --second rule calculates projected values for 2002
          nr[ANY, 2002, ANY] = ROUND(
             ((nr[CV(),2001,CV()] - nr[CV(),2000, CV()])
              / nr[CV(),2000, CV()]) * nr[CV(),2001, CV()]
             + nr[CV(),2001, CV()],2),
                          --third rule converts 2002 projections to US dollars
          nr[ANY,y != 2002,ANY]
             = ROUND(nr[CV(),CV(),CV()]
               * curr_conversion.to_us[ cc[CV(),CV(),CV()], CV(y), CV(m)], 2)
    ORDER BY c, p, y, m)
    WHERE y = '2002'
    ORDER BY c, p, y, m;I got the following error:
    ORA-00947: not enough values
    00947. 00000 -  "not enough values"
    *Cause:   
    *Action:
    Error at Line: 39 Column: 83But when I changed the part
    curr_conversion.to_us[ cc[CV(),CV(),CV()], CV(y), CV(m)], 2) of 3.rd Rules to
    curr_conversion.to_us[ cc[CV(),CV(),CV()] || '', CV(y), CV(m)], 2)or
    curr_conversion.to_us[ cc[CV(),CV(),CV()] || null, CV(y), CV(m)], 2)It worked!
    My questions:
    1/Can anyone explain me why it worked and why it didn't work?
    2/Rule 3 has not the same meaning as the comment, Is it an error? Or I misunderstood anything?
    the comment is: third rule converts 2002 projections to US dollars the left side has y != 2002 Thank for any help !
    regards
    hqt200475
    Edited by: hqt200475 on Dec 20, 2012 4:45 AM

  • SQL model clause not working when dimensioned on a char or a varchar2 colum

    Hi ,
    I tried to execute the below mentioned query and this returns me columns from monday to sunday values as null.
    select weekno
    , empno
    , mon
    , tue
    , wed
    , thu
    , fri
    , sat
    , sun
    from worked_hours
    model
    return updated rows
    partition by (weekno, empno)
    dimension by ( day )
    measures ( hours,lpad(' ',3) mon,lpad(' ',3) tue, lpad(' ',3) wed,lpad(' ',3) thu,lpad(' ',3) fri,lpad(' ',3) sat,lpad(' ',3) sun)
    RULES upsert
    mon [0] = hours [1]
    , tue [0] = hours [2]
    , wed [0] = hours [3]
    , thu [0] = hours [4]
    , fri [0] = hours [5]
    , sat [0] = hours [6]
    , sun [0] = hours [7]
    In the initial example day is a number and when executed the above query it works. The result set is as below :-
    WEEKNO EMPNO MON TUE WED THU FRI SAT SUN
    1 1210 8 7.5 8.5 4.5 8
    1 1215 2 7.5 8 7.5 8
    When the data type of day is changed to char and populated with the right values then the result set looks as below :-
    WEEKNO EMPNO MON TUE WED THU FRI SAT SUN
    1 1210
    1 1215
    Can anyone help me resolve this ?
    --XXXXX                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    user10723455 wrote:
    Hi ,
    When the data type of day is changed to char and populated with the right values then the result set looks as below :- Can not reproduce on 10.2.0.4.0:
    SQL> select * from v$version
      2  /
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - Prod
    PL/SQL Release 10.2.0.4.0 - Production
    CORE    10.2.0.4.0      Production
    TNS for 32-bit Windows: Version 10.2.0.4.0 - Production
    NLSRTL Version 10.2.0.4.0 - Production
    SQL> create table worked_hours_char as select * from worked_hours where 1 = 2
      2  /
    Table created.
    SQL> alter table worked_hours_char modify day char(10)
      2  /
    Table altered.
    SQL> insert into worked_hours_char select * from worked_hours
      2  /
    14 rows created.
    SQL> commit
      2  /
    Commit complete.
    SQL> select weekno
      2  , empno
      3  , mon
      4  , tue
      5  , wed
      6  , thu
      7  , fri
      8  , sat
      9  , sun
    10  from worked_hours
    11  model
    12  return updated rows
    13  partition by (weekno, empno)
    14  dimension by ( day )
    15  measures ( hours,lpad(' ',3) mon,lpad(' ',3) tue, lpad(' ',3) wed,lpad(' ',3) thu,lpad(' ',3) fri,lpad(' ',3) sat,lpad(' ',3) su
    n)
    16  RULES upsert
    17  (
    18  mon [0] = hours [1]
    19  , tue [0] = hours [2]
    20  , wed [0] = hours [3]
    21  , thu [0] = hours [4]
    22  , fri [0] = hours [5]
    23  , sat [0] = hours [6]
    24  , sun [0] = hours [7]
    25  )
    26  /
        WEEKNO      EMPNO MON TUE WED THU FRI SAT SUN
             1       1210 8   7.5 8.5 4.5 8
             1       1215 2   7.5 8   7.5 8
    SQL> select weekno
      2  , empno
      3  , mon
      4  , tue
      5  , wed
      6  , thu
      7  , fri
      8  , sat
      9  , sun
    10  from worked_hours_char
    11  model
    12  return updated rows
    13  partition by (weekno, empno)
    14  dimension by ( day )
    15  measures ( hours,lpad(' ',3) mon,lpad(' ',3) tue, lpad(' ',3) wed,lpad(' ',3) thu,lpad(' ',3) fri,lpad(' ',3) sat,lpad(' ',3) su
    n)
    16  RULES upsert
    17  (
    18  mon [0] = hours [1]
    19  , tue [0] = hours [2]
    20  , wed [0] = hours [3]
    21  , thu [0] = hours [4]
    22  , fri [0] = hours [5]
    23  , sat [0] = hours [6]
    24  , sun [0] = hours [7]
    25  )
    26  /
        WEEKNO      EMPNO MON TUE WED THU FRI SAT SUN
             1       1210 8   7.5 8.5 4.5 8
             1       1215 2   7.5 8   7.5 8
    SQL> SY.

  • Help with over by clause in query.

    guys i have a table like this
    create table fgbtrnh ( fgbtrnh_doc_code varchar2(9),
                                             fgbtrnh_trans_date date,
                                             fgbtrnh_trans_amt number(17,2),
                                             fgbtrnh_acct varchar2(6) ,
                                             fgbtrnh_fund_code varchar2(6),
                                             fgbtrnh_rucl_code varchar2(6) );
    with data like this.
       insert into fgbtrnh( fgbtrnh_doc_code,fgbtrnh_trans_date,fgbtrnh_trans_amt,fgbtrnh_acct,fgbtrnh_rucl_code,fgbtrnh_fund_code) values('J0005445','31-MAY-10','38491','6001','BD01','360098');
    insert into fgbtrnh( fgbtrnh_doc_code,fgbtrnh_trans_date,fgbtrnh_trans_amt,fgbtrnh_acct,fgbtrnh_rucl_code,fgbtrnh_fund_code) values('L0000005','01-JUL-08','38260','6001','BD01','360098');
    insert into fgbtrnh( fgbtrnh_doc_code,fgbtrnh_trans_date,fgbtrnh_trans_amt,fgbtrnh_acct,fgbtrnh_rucl_code,fgbtrnh_fund_code) values('L0000002','30-JUN-08','24425.29','6001','BD01','360125');
    insert into fgbtrnh( fgbtrnh_doc_code,fgbtrnh_trans_date,fgbtrnh_trans_amt,fgbtrnh_acct,fgbtrnh_rucl_code,fgbtrnh_fund_code) values('L0000002','30-JUN-08','48057.71','6001','BD01','360125');
    insert into fgbtrnh( fgbtrnh_doc_code,fgbtrnh_trans_date,fgbtrnh_trans_amt,fgbtrnh_acct,fgbtrnh_rucl_code,fgbtrnh_fund_code) values('M0000002','30-JUN-08','90','7200','BD01','360098');i would like to get a running total of these items so i tried something like this.
    select  f.fgbtrnh_doc_code,f.fgbtrnh_trans_date,f.fgbtrnh_trans_amt, sum(f.fgbtrnh_trans_amt)
    over
    (--partition by  f.fgbtrnh_doc_code
    order by fgbtrnh_trans_date desc  ROWS UNBOUNDED PRECEDING
    --group by  f.fgbtrnh_doc_code
    )total
    From fgbtrnh f
    where f.fgbtrnh_fund_code in ('360098', '360125')
    and f.fgbtrnh_rucl_code = 'BD01'
    and f.fgbtrnh_acct = '6001'
    order by  f.fgbtrnh_trans_date desc,  f.fgbtrnh_doc_codebut i end up with a result set like
    "FGBTRNH_DOC_CODE", "FGBTRNH_TRANS_DATE", "FGBTRNH_TRANS_AMT", "TOTAL"
    "J0005445", 31-MAY-10, 38491, 38491
    "L0000005", 01-JUL-08, 38260, 76751
    "L0000002", 30-JUN-08, 24425.29, 101176.29
    "L0000002", 30-JUN-08, 48057.71, 149234
    i would like to thave the running total to start from the bottom in other word is my total column i would like to end up with the 149234 at the top
    so it would look something like so.
    "FGBTRNH_DOC_CODE", "FGBTRNH_TRANS_DATE", "FGBTRNH_TRANS_AMT", "TOTAL"
    "J0005445", 31-MAY-10, 38491, 149234
    "L0000005", 01-JUL-08, 38260, 110743
    "L0000002", 30-JUN-08, 24425.29, 72483
    "L0000002", 30-JUN-08, 48057.71, 48057.71
    i have tried everything and just cant seem to make this work can someone please point me in the rigth direction.
    I would really appreciate the help.
    Thanks
    Miguel

    Hi, Miguel,
    mlov83 wrote:
    ... Also, if you uniquely order the rows, you won't need the windowing clause ("ROWS UNBOUNDED PRECEEDING"); the default ("RANGE UNBOUNDED PRECEDING") will produce exactly what you want, so you don;'t need to say it.
    I dont really understand what you mean by this ? but if i take a gander are you saying that all my rows would have to be unique and then i wont have to use ("ROWS UNBOUNDED PRECEEDING")I think you got it right.
    The analytic ORDER BY clause doesn't have to result in a unique ordering; there are good reasons for having a unique oprdering, and there are good reasons for not having a unique ordering.
    I'm saying that if the analytic ORDER BY is unique, then you don't need to give a widnowing clause, such as "ROWS UNBOUNDED PRECEEDING".
    Frank sorry if im asking some really stupid questions but i have tried and tried to read and understand "partion by" and "over" work but im not quite sure I understand yet. It's not stupid at all! Analytic functions can be very subtle and confusing.
    Let's use a query based on the scott.emp table, which has seveal rows for each deptno.
    -- Tell SQL*Plus to put a blank line between deptnos, just to make the output easier to read
    BREAK     ON deptno   SKIP 1     DUPLICATES
    SELECT       deptno
    ,       ename
    ,       sal
    ,       SUM (sal) OVER ( PARTITION BY  deptno
                                ORDER BY        sal
                      ROWS            UNBOUNDED PRECEDING
                    )     AS running_total
    FROM       scott.emp
    ORDER BY  deptno
    ,            sal          DESC
    ,       ename
    ;Output:
    `   DEPTNO ENAME             SAL RUNNING_TOTAL
            10 KING             5000          8750
            10 CLARK            2450          3750
            10 MILLER           1300          1300
            20 FORD             3000         10875
            20 SCOTT            3000          7875
            20 JONES            2975          4875
            20 ADAMS            1100          1900
            20 SMITH             800           800
            30 BLAKE            2850          9400
            30 ALLEN            1600          6550
            30 TURNER           1500          4950
            30 MARTIN           1250          2200
            30 WARD             1250          3450
            30 JAMES             950           950PARTITION BY deptno" means do a separate calculation for each distinct value of deptno. Rows with deptno=10 don't effect the results on rows where deptno=20 or deptno=30. Since there are 3 distinct values of deptno, there are 3 distinct running totals.
    Notice that the aNalytic ORDER BY clause results only in a partial ordering. If there are two or more rows in the same deptno that happen to have the same sal, look what can happen:
    {code}
    ` DEPTNO ENAME SAL RUNNING_TOTAL
    ... 30 TURNER 1500 4950
    30 MARTIN 1250 2200
    30 WARD 1250 3450
    30 JAMES 950 950
    {code}
    MARTIN and WARD are in the same partition (deptno=30), and they both have the same sal (1250), so there is no reason why one of those rows would be considered "before" the other one. When you use a windowing clause based on ROWS, as above, and there is a tie for whcih row comes first (as there is a tie between MARTIN and WARD), then one of the rows will arbitrarily be condidered to be before the other one. In this example, it happened to chose MARTIN as the 2nd lowest sal, so running_total=2200 (= 950 + 1250) on the row for MARTIN, and running_total=3450 ( = 950 + 1250 + 1250) on the row for WARD. There's no particular reason for that; it's completely arbitrary. I might do the exact same query tomorrow, or in 10 minutes, and get running_total=2200 on WARD's row, and 3450 on MARTIN's.
    However, it is no accident that MARTIN comes before WARD in the output; the *query* ORDER BY clause (which has nothing to do with the analytic ORDER BY clause) guarantees that, when two rows have the same deptno and sal, then the one with the earlier ename will come first.
    Now, what's the difference between a window based on ROWS and a window bnased on RANGE?
    One difference is that, when a tie occurs in the ORDER BY clause, all rows with the same value of sal get the same value for SUM (sal):
    {code}
    SELECT     deptno
    ,     ename
    ,     sal
    ,     SUM (sal) OVER ( PARTITION BY deptno
                   ORDER BY      sal
                   )     AS running_total
    FROM     scott.emp
    ORDER BY deptno
    ,      sal          DESC
    ,     ename
    {code}
    Notice that the only difference between the first query above and this one is that this one does not have an analytic windowing clause, so the default window, *RANGE* UNBOUNDED PRECEDING is used.
    Output:
    {code}
    ` DEPTNO ENAME SAL RUNNING_TOTAL
    10 KING 5000 8750
    10 CLARK 2450 3750
    10 MILLER 1300 1300
    20 FORD 3000 10875
    20 SCOTT 3000 10875
    20 JONES 2975 4875
    20 ADAMS 1100 1900
    20 SMITH 800 800
    30 BLAKE 2850 9400
    30 ALLEN 1600 6550
    30 TURNER 1500 4950
    30 MARTIN 1250 3450
    30 WARD 1250 3450
    30 JAMES 950 950
    {code}
    Again, look at MARTIN and WARD near the end. They both have the ame sal, so they both have the same running_total=3450 (= 950 + 1250 + 1250). This is often a desireable result, but, in your case, it seems not to be. If you want separate running_totals for MARTIN and WARD, then you eigher have to use a ROW-based window, like we did earlier, or add a tie-breaker to the ORDER BY clause, like this:
    {code}
    SELECT     deptno
    ,     ename
    ,     sal
    ,     SUM (sal) OVER ( PARTITION BY deptno
                   ORDER BY      sal
                   ,          ename          DESC     -- Changed (this is the only change)
                   )     AS running_total
    FROM     scott.emp
    ORDER BY deptno
    ,      sal          DESC
    ,     ename
    {code}
    Output:
    {code}
    ` DEPTNO ENAME SAL RUNNING_TOTAL
    10 KING 5000 8750
    10 CLARK 2450 3750
    10 MILLER 1300 1300
    20 FORD 3000 10875
    20 SCOTT 3000 7875
    20 JONES 2975 4875
    20 ADAMS 1100 1900
    20 SMITH 800 800
    30 BLAKE 2850 9400
    30 ALLEN 1600 6550
    30 TURNER 1500 4950
    30 MARTIN 1250 3450
    30 WARD 1250 2200
    30 JAMES 950 950
    {code}

  • Help with SQL*Plus COPY Command syntax

    Hello people.
    DBs are 10g
    PROD DB is a remote DB (over DB Link)
    TEST DB is where my SQL*Plus is logged in.
    LOCAL_DB_TABLE is the table I need to create to TEST DB
    REMOTE_DB _TABLE is the table that already exists in remote PROD DB
    COPY FROM replica/replica@PROD
    CREATE LOCAL_DB_TABLE@TEST
    ROW_ID,
    CREATED,
    CREATED_BY,
    UPD,
    UPD_BY
    USING SELECT
    ROW_ID,
    CREATED,
    CREATED_BY,
    UPD,
    UPD_BY
    FROM REMOTE_DB_TABLE
    WHERE ROW_ID='XXX';The error message I am getting:
    usage: COPY FROM <db> TO <db> <opt> <table> { (<cols>) } USING <sel>
      <db>   : database string, e.g., hr/your_password@d:chicago-mktg
      <opt>  : ONE of the keywords: APPEND, CREATE, INSERT or REPLACE
      <table>: name of the destination table
      <cols> : a comma-separated list of destination column aliases
      <sel>  : any valid SQL SELECT statement
    A missing FROM or TO clause uses the current SQL*Plus connection.
    CREATE LOCAL_DB_TABLE@TEST
    ERROR at line 1:
    ORA-00901: invalid CREATE commandThank you in advance for your help.

    Hi,
    I hope you are thinking of Creating a Table with the Same Structure as the remote database Table, If so.
    You can create a Table from the Existing Table using CTAS(Create Table as Select).
    Provided, you have created a Database Links between the 2 Databases. You can create a
    table in your Schema as,
    CREATE TABLE local_db_table AS
    SELECT * FROM remote_user_name.remote_db_table@dbname;Thanks,
    Shankar
    Edited by: Shankar Viji on Jul 19, 2012 11:01 PM

Maybe you are looking for

  • Memory full error

    I'm getting "memory full error" during generation of report. CR version is 8.5. The report contains 2 sub reports. Can anyone suggest what exactly the problem is and what could be the solution ... ?? Thanks in advance ...

  • IMAGE PROCESSOR problem typing changes

    IMAGE PROCESSOR with CS5 both snow leopard and lion : I'm trying to set up a batch resizing script : after selecting both folders, checking "resize to fit", "save as jpeg", I can't type in any new settings for quality or W px. Keyboard makes error so

  • Macbook Pro Retina Display, a rough spot on the screen.!!!

    I bought my Macbook Pro (Retina Display) from a Authorised Reseller in Malidves. Its been 3 weeks since i've bought it. Few days back i noticed a white spot on the screen. I tried to wipe the spot off with the cleaning cloth. to my surprise, the spot

  • Why is the sound quality on my laptop so bad?

    Hello. I have an HP Envy 17t-j100 with windows 8.1. I have noticed that anything I play on my laptop is lower quality to anything I play on any other device. I used the same headphones. My guess is it has something to do with the beats audio. If i un

  • HAS ANYONE ELSE NOTICED THIS WITH MAVERICKS

    I can't help but notice since I loaded Mavericks, that my Mac is running way too much. It runs and rattles away like I'm calculating the postion of each star in the galaxie. I have never heard it work so hard, and It's not even doing anything. It's l