Calculations Using SQL Query

Hi All,
I am using Oracle Database Version 11.2.
I have a formula (A-B)/[(A-B)/10]. The tables that are holding the rows for this calculations are given below:
ROWS_TAB
====== ===================
Row          Amount
====== ===================
A            5000
B            -5000
FORMULA_TAB
======== =========== ======== =============
| ROW#  | Operator            | ROW        |   CONSTANT   |
======== =========== ======== =============
| 10        |     E                   |      A       |                         |
| 20        |     -                    |     B        |                         |
| 30        |     E                   |      A       |                         |
| 40        |     -                    |     B        |                         |
| 50        |     /                    |               |      10                |
| 60        |    /                     |               |                          |
======== =========== ======== =============
The operator E starts a new calculation. The above formula has two sub-expressions thereby the table has two rows with E. Minus denoted by -, Plus denoted by +, Multiply denoted by *, and Division denoted by /.
I want to write single SQL query to perform this calculation. Is it achievable in SQL?
The scripts used to generate the tables are as below:
create table ROWS_TAB
(row_name VARCHAR2(1),
amount NUMBER);
create table FORMULA_TAB
(row# NUMBER,
operator VARCHAR2(1),
row_name VARCHAR2(1),
constant NUMBER);
INSERT INTO ROWS_TAB VALUES('A', 5000);
INSERT INTO ROWS_TAB VALUES('B', -5000);
INSERT INTO FORMULA_TAB VALUES(10, 'E','A',null);
INSERT INTO FORMULA_TAB VALUES(20, '-','B',null);
INSERT INTO FORMULA_TAB VALUES(30, 'E','A',null);
INSERT INTO FORMULA_TAB VALUES(40, '-','B',null);
INSERT INTO FORMULA_TAB VALUES(50, '/','',10);
INSERT INTO FORMULA_TAB VALUES(60, '/','','');
Can anyone help in writing SQL query....
Thanks in advance
Best Regards
Bilal

As Frank said, it would be much easier to simply input the formula. Then, assuming you have OLAP option:
variable formula varchar2(30)
exec :formula := '(A-B)/((A-B)/10)';
with t as (
           select  *
             from  rows_tab
             model
               dimension by(row_number() over(order by row_name) r)
               measures(
                        row_name,
                        amount,
                        count(*) over() cnt,
                        cast(:formula as varchar2(4000)) formula
               rules(
                     formula[any] order by r = replace(nvl(formula[cv() - 1],formula[cv()]),row_name[cv()],amount[cv()])
select  :formula || ' = ' || dbms_aw.eval_number(formula) result
  from  t
  where r = cnt
RESULT
(A-B)/((A-B)/10) = 10
SQL>
And if you do not have OLAP, you could use xquery:
with t as (
           select  *
             from  rows_tab
             model
               dimension by(row_number() over(order by row_name) r)
               measures(
                        row_name,
                        amount,
                        count(*) over() cnt,
                        cast(:formula as varchar2(4000)) formula
               rules(
                     formula[any] order by r = replace(nvl(formula[cv() - 1],formula[cv()]),row_name[cv()],amount[cv()])
select  :formula || ' = ' || xmlquery(replace(formula,'/',' div ') returning content) result
  from  t
  where r = cnt
RESULT
(A-B)/((A-B)/10) = 10
SQL>
SY.

Similar Messages

  • Creating a ad-hoc calculation using sql query

    Hi All,
    I want to know if its possible some way to create a ad-hoc sql query inside a workbook so as to create a calculation using that sql.
    I have a folder which gives me balance for any period. My requirement is to display current period balance along with prior years closing balance in same record for each code combination. I dont want to modify folder definition.
    Thanks for your inputs.
    Vishal.

    You could try creating a custom function for this purpose. You would need to register the function in the End User Layer and then you can call the function from your report.

  • Dataload using sql query

    Hi,
    i need to load the data using sql query in to essbase cube by using maxl .If any one knows this please let me know.
    i
    thanks in advance

    Here is a sample maxl script I use to clear, load, and calculation a BSO Application and Database. Both the Application and Database are titled "STAT_2".
    /*** Login to essbase server ***/
    /*** login $1 $2 on $3; ***/
    login 'username 'password' on 'server';
    /*** Set output file to spool all error messages only ***/
    spool stdout on to 'C:\Hyperion\Automation\Logs\STAT_2_ALL_Load_Essbase.LOG';
    spool stderr on to 'C:\Hyperion\Automation\Errors\STAT_2_ALL_Load_Essbase.ERR';
    /*** Clear data in STAT_2 ***/
    /** execute calculation 'STAT_2'.'STAT_2'.'ClrA2Yr'; **/
    /*** Import data from the FACT_STAT_2YEARS table using a load rule ***/
    import database 'STAT_2'.'STAT_2' data connect as 'SQLUserName' identified by 'SQLPassword' using server rules_file 'LdA_All.rul' on error write to 'C:\Hyperion\Automation\Logs\STAT_2_ALL_Load_Essbase.log';
    /*** Calculate data in STAT_2 ***/
    /** execute calculation 'STAT_2'.'STAT_2'.'ClcA2Yr'; ***/
    spool off;
    logout;
    exit;

  • Retreving Hexadecimal Values from a table using SQL query.

    Hi,
    I'm looking for a query to retreive Hexadecimal values contained in a column using SQL query.
    The column contains the values of all types, alphanumeric, numeric and hexadecimal.
    I need to retreive only hexadecimal values.
    any help to me in this regard will be appreciated.
    Thanks

    Presumably, you can be sure that any valid hex value is indeed MEANT to BE a hex value. For example the value 'ACE' is meant to be a hexadecimal value and not the word.

  • How to get tax break up of TDS using SQL query ?

    Hi all,
    We are developing a TDS report using SQL query
    Report will contain VendorCode,Date(ap inv date),Vendor name,
    Bill value,TDS Amount,
    Bill Value – 100.000,
    TDS (2%) - 2.000,
    TDS Surcharge(10% on TDS) - 0.2,
    TDS Cess(2%(TDS+TDS Surcharge)) - 0.044,
    TDS HeCess(1%(TDS+TDS Surcharge)) - 0.022.
    We have developed this report which displays upto
    VendorCode,Date(ap inv date),Vendor name,
    Bill value,TDS Amount.
    How to show tax break up of TDS in SQL query ?
    Thanks,
    With regards,
    Jeyakanthan.

    Hi gauraw,
    Thank for your reply.
    I modified the query , pasted the query
    as below in query generator,
    Select T0.DocNum,T0.DocDate,T0.CardCode as 'Ledger',T1.TaxbleAmnt As 'Bill value',T1.WTAmnt as 'TDSAmt',(TDSAmt * 0.1) as 'TDS_Surch',
    (((TDSAmt0.1) + TDSAmt)0.02)  as 'TDSCess',
    (((TDSAmt0.1) + TDSAmt)0.01)  as 'TDSHCess'
    FROM OPCH T0  INNER JOIN PCH5 T1 ON T0.DocEntry = T1.AbsEntry
    WHERE (T0.DocDate >= '[%0]' and T0.DocDate <= '[%1]')
    on clicking execute its showing error message invalid column
    name 'TDSAmt'.
    With regards,
    Jeyakanthan

  • Help Required -- Can we use SQL Query to READ data from SAP MDM Tables

    Hi All,
    Please help.........
    Can we use SQL Query to READ(No Creation/Updation/Deletion  just Read) Data from SAP MDM tables directly, without using MDM Syndicator.
    Or direct SQL access to SAP MDM tables is not possible. Only through MDM Syndicator can we export data.
    Thanks in Advance
    Regards

    All the tables you create in Repository comes under A2i_CM_Tables in Database named as your repository name. So the tables names are fields of table A2i_CM_Tables. Now i tried it but cant make it.
    Now, I dont think its possible to extract all fields in tables and there values using select query. May be pure sql guy can do that or not.
    But there is no relation of data extraction and syndicator. Data is viewed in Data Manager. and you can also store data in a file from DM also.
    BR,
    Alok

  • How to retrive the blob data from a table using sql query

    Hi gurus,
    I have a table which has " BLOB "content in a column .I want to view the data From BLOB column using sql query .It would be helpfull If some one share their idea.
    Regards,
    vardhani.

    You can use data templates.
    See this: http://blogs.oracle.com/xmlpublisher/entry/blob_clob_raw_and_looooong
    http://blogs.oracle.com/xmlpublisher/entry/inserting_blobs_into_your_repo
    Thanks,
    Bipuser

  • How to use sql query in java ?

    i don't know how to use sql query in java code.
    who can give me some advice?
    thanks

    http://java.sun.com/developer/onlineTraining/Database/JDBC20Intro/

  • How do i get the approximate size of back up file required to save on disk using sql query because i want to show the required sapce for backup on my application

    hi i am face with problem that is i want to show the how much approximate space required for backup or .bak file to get backup using sql query because i want to show the required memory for backup file on my java application  

    Hi FIROZ
    TENNALI
    Is this still an issue, or can we close the thread?
    * closing a thread by marking the answer/s (there is a link beneath each response) and you can vote for useful responses as well (there is a link to vote on the left of each response)
      Ronen Ariely
     [Personal Site]    [Blog]    [Facebook]

  • How to Use SQL Query having IN Clause With DB Adapter

    Hi,
    I am using 11.1.1.5 want to find out how to Use SQL Query having IN Clause With DB Adapter. I want to pass the IN values dynamically. Any ideas.
    Thanks

    invoke a stored procedure, it's safer than trying to put together an arbitrary SQL statement in the JCA adapter

  • Using SQL query on user defined table

    Hi all,
    i'am currently working on a project which use user defined table and i would like to know if sap allow us to do insertion/deletion/update on those table using sql query or if we have to use the DI only?
    thanks
    Best regards,

    Hi,
    Definitely you can insert in UDT. You can update but you cant change the Code field after added the rest of the field
    can be updated. You cant delete in UDT but you cant delete anytime in SQL Management Studio.
    THanks.
    CLint

  • How to numberformat when using sql:query alogn with c:forEach JSTL tags

    Is there anyway to format the numeric values returned from the database when using <sql:query> alogn with <c:forEach> tags
    Here is my jsp code
    <sql:query..../>
    <c:forEach var="row" items="${queryResults.rows}">
    <tr>
    <td><c:out value="${row.COL1}" /></td>
    <td><c:out value="${row.COL2}" /></td>
    </tr>
    </c:forEach>
    Col1 values are numeric without any formats Eg: 1000, 10000, 1000000 etc.
    how can i format them to 1,000 , 10,1000 , 100,000 etc

    It is polite to mention what your answer was. These posts are not just here for you to ask questions, but to be used as a resource for other people to find answers. Saying "I solved it" with no details helps noone.
    I presume you discovered the JSTL <fmt:formatNumber> tag?

  • List of Project Permission in PS 2010 Using SQL query

    Hi
    Is there any way to get a list of Project permissions associated with user using sql query. If i go manually Project center --> select project plan --> project permission it would take lot of time to find out for each user
    Regards
    Santosh

    Before you continue (which you probably will overlook) - please understand that you should only be querying the REPORTING database and not the published database.  A recommendation is to use a select statement statement to insert the tables into a table
    int the reporting database, then query that table for your results/report.  
    The following page I believe has what you're looking for (Users with direct permissions- query below)
    and more
    http://pmpspecialists.com/Blog/2013/10/
    SELECT MSP_RESOURCES.RES_NAME AS Resourcename, CONV.CONV_STRING AS Permission, MSP_WEB_SECURITY_SP_CAT_PERMISSIONS.WSEC_DENY AS Denied,
    MSP_WEB_SECURITY_SP_CAT_PERMISSIONS.WSEC_ALLOW AS Allowed
    FROM MSP_WEB_SECURITY_SP_CAT_PERMISSIONS INNER JOIN
    MSP_WEB_SECURITY_SP_CAT_RELATIONS ON
    MSP_WEB_SECURITY_SP_CAT_PERMISSIONS.WSEC_REL_UID = MSP_WEB_SECURITY_SP_CAT_RELATIONS.WSEC_REL_UID INNER JOIN
    MSP_WEB_SECURITY_FEATURES_ACTIONS ON
    MSP_WEB_SECURITY_FEATURES_ACTIONS.WSEC_FEA_ACT_UID = MSP_WEB_SECURITY_SP_CAT_PERMISSIONS.WSEC_FEA_ACT_UID INNER JOIN
    MSP_WEB_CONVERSIONS AS CONV ON CONV.CONV_VALUE = MSP_WEB_SECURITY_FEATURES_ACTIONS.WSEC_FEA_ACT_NAME_ID INNER JOIN
    MSP_RESOURCES ON MSP_WEB_SECURITY_SP_CAT_RELATIONS.WSEC_SP_GUID = MSP_RESOURCES.RES_SECURITY_GUID
    WHERE (CONV.LANG_ID = 1033)
    ORDER BY Resourcename, Permission

  • How to show the VALUE as the Column Header using SQL query?

    Hi
    I have a requirement to show the picked value as the column header using SQL query.
    Example:
    ======
    SELECT EMPNO FROM EMP
    WHERE EMPNO=7934;
    Result Should be:
    7934
    7934

    I have a requirement to show the picked value as the column header using SQL query.In sql*plus you can do
    SQL> set verify on
    SQL> def e =  7934
    old: SELECT empno "&&e"  FROM emp  WHERE empno = &&e
    new: SELECT empno "7934"  FROM emp  WHERE empno = 7934
    SQL> SELECT empno "7934"  FROM emp  WHERE empno = 7934
          7934
          7934
    1 row selected.

  • How to backup database using sql query?

    Hello,i'm student, i'm researching oracle database,i want to backup database that using sql query (like backup query in SQL SERVER) ,how to do that ??
    Thank!

    No, database backups cannot be done from within the database.
    Commands for backups are outside of the database.
    See the "2 Day DBA Guide" http://download.oracle.com/docs/cd/E11882_01/server.112/e10897/toc.htm
    and the "Backup and Recovery Users's (actually Adminsitrator's) Guide : http://download.oracle.com/docs/cd/E11882_01/backup.112/e10642/toc.htm
    Hemant K Chitale

Maybe you are looking for