Sql problem, pivot question?
Hi guys,
I have an interesting problem and do not manage to find a sollution.
I need to create a report, and we call it variance/trending report. let me explain.
I have a table that holds all employess with their salaries, every month.
currenly my selects gets all employess with their salaries from current and previous month. and the result looks like:
Employee_iD| Salary| month
1 |500 | C
2 |100 | P
1 |650 | P
3 |100 | p
3 |180 | C
how can I do my select so I can see the result, in different columns, in a manner in which I can compare the salaries between them (from current and previous month):
Employe_iD| current_month| previous_month | variance
1 |500 | 650 | -150
2 | | 100 |
3 |180 |100 |80you can see that C, measn current month, and P measn previous month.
I think I will have data in my select for both, previous and current. If not, I will treat it as zero.
I gave a simple exemple . My select is a little more complex.
any help is appreciated.
Thanks
May be..
SQL> WITH tbl AS (SELECT 1 empid,500 sal,'C' mon FROM DUAL UNION ALL
2 SELECT 2 empid,100 sal,'P' mon FROM DUAL UNION ALL
3 SELECT 1 empid,650 sal,'P' mon FROM DUAL UNION ALL
4 SELECT 3 empid,100 sal,'P' mon FROM DUAL UNION ALL
5 SELECT 3 empid,180 sal,'C' mon FROM DUAL
6 )
7 SELECT empid,NVL(MAX(DECODE(mon,'P',sal)),0) previous_sal
8 ,NVL(MAX(DECODE(mon,'C',sal)),0) current_sal
9 ,NVL(MAX(DECODE(mon,'P',sal)),0)- NVL(MAX(DECODE(mon,'C',sal)),0)
10 var
11 FROM tbl
12 GROUP BY empid
13 ;
EMPID PREVIOUS_SAL CURRENT_SAL VAR
1 650 500 150
2 100 0 100
3 100 180 -80
Similar Messages
-
Embedded SQL against Oracle Question
Software: Forte 3.0.J.
Server Platform: HPUX 10.2
Database: Oracle
Problem Description: During the course of development, I ran into a
problem using multiple columns in an sql UPDATE/SET statement. I was trying
to update a.COLUMN_1 and a.COLUMN_2, which constitute part of the primary
key of associative TABLE_A (a). In order for me to make the update, I
needed to use the existing value of a.COLUMN_1 to lookup the new b.COLUMN_1
in TABLE_B (b). Where a.COLUMN_1 = b.RELATED_COLUMN_1, I am able to find
each b.COLUMN_2 that correspond to each a.COLUMN_2.
I was able to resolve the issue by separating the two columns so
that each had it's own select statement. Theoretically, it appears that
this shouldn't work, because the SET statement for a.COLUMN_1 would cause
the a.COLUMN_1 reference in the select statement of a.COLUMN_2 to be
overwritten.
In spite of this, I tried it, and it worked. I would like to
understand why the sql works, and how sql actually executes the statement.
Here is the sql:
UPDATE TABLE_A a
SET a.COLUMN_1 =
(SELECT DISTINCT b1.COLUMN_1
FROM TABLE_B b1
WHERE b1.RELATED_CASE_ID =
a.COLUMN_1 AND
b1.RELATED_COLUMN_TYPE_CD = 'NEPHI'),
a.COLUMN_2=
(SELECT DISTINCT b2.COLUMN_2
FROM TABLE_B b2
WHERE b2.RELATED_COLUMN_1=
a.COLUMN_1 AND
b2.RELATED_COLUMN_TYPE_CD = 'NEPHI' AND
b2.RELATED_COLUMN_2= a.COLUMN_2)
WHERE a.COLUMN_1 = 100
The table structure is as follows:
TABLE_A: (primary keys are bolded) This is an associative table.
Column_1 and Column_2 comprise the pk of one table; Column_3 and Column_4
comprise the pk of another table. Assume that the Column_1 and Column_2
values replacing the original values already exist in the parent table of
which they form the pk).
COLUMN_1
COLUMN_2
COLUMN_3
COLUMN_4
COLUMN_5
TABLE_B: (primary keys are bolded) This is a reference table.
COLUMN_1
COLUMN_2
RELATED_COLUMN_1
RELATED_COLUMN_2
RELATED_COLUMN_TYPE_CD
To unsubscribe, email '[email protected]' with
'unsubscribe forte-users' as the body of the message.
Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/>If you do an explain plan or set autotrace on against this update statement,
you'll find that the select operations are actually executed first by Oracle
- I believe because of the nature of the transaction. Thus, no problem.
Brian Wilson
U.S. Bancorp Piper Jaffray
[email protected]
Phone (612) 342-5682
From: David Pettit[SMTP:[email protected]]
Reply To: David Pettit
Sent: Friday, April 30, 1999 1:58 PM
To: '[email protected]'
Subject: Embedded SQL against Oracle Question
Software: Forte 3.0.J.
Server Platform: HPUX 10.2
Database: Oracle
Problem Description: During the course of development, I ran into a
problem using multiple columns in an sql UPDATE/SET statement. I was
trying
to update a.COLUMN_1 and a.COLUMN_2, which constitute part of the primary
key of associative TABLE_A (a). In order for me to make the update, I
needed to use the existing value of a.COLUMN_1 to lookup the new
b.COLUMN_1
in TABLE_B (b). Where a.COLUMN_1 = b.RELATED_COLUMN_1, I am able to find
each b.COLUMN_2 that correspond to each a.COLUMN_2.
I was able to resolve the issue by separating the two columns so
that each had it's own select statement. Theoretically, it appears that
this shouldn't work, because the SET statement for a.COLUMN_1 would cause
the a.COLUMN_1 reference in the select statement of a.COLUMN_2 to be
overwritten.
In spite of this, I tried it, and it worked. I would like to
understand why the sql works, and how sql actually executes the statement.
Here is the sql:
UPDATE TABLE_A a
SET a.COLUMN_1 =
(SELECT DISTINCT b1.COLUMN_1
FROM TABLE_B b1
WHERE b1.RELATED_CASE_ID =
a.COLUMN_1 AND
b1.RELATED_COLUMN_TYPE_CD = 'NEPHI'),
a.COLUMN_2=
(SELECT DISTINCT b2.COLUMN_2
FROM TABLE_B b2
WHERE b2.RELATED_COLUMN_1=
a.COLUMN_1 AND
b2.RELATED_COLUMN_TYPE_CD = 'NEPHI' AND
b2.RELATED_COLUMN_2= a.COLUMN_2)
WHERE a.COLUMN_1 = 100
The table structure is as follows:
TABLE_A: (primary keys are bolded) This is an associative table.
Column_1 and Column_2 comprise the pk of one table; Column_3 and Column_4
comprise the pk of another table. Assume that the Column_1 and Column_2
values replacing the original values already exist in the parent table of
which they form the pk).
COLUMN_1
COLUMN_2
COLUMN_3
COLUMN_4
COLUMN_5
TABLE_B: (primary keys are bolded) This is a reference table.
COLUMN_1
COLUMN_2
RELATED_COLUMN_1
RELATED_COLUMN_2
RELATED_COLUMN_TYPE_CD
To unsubscribe, email '[email protected]' with
'unsubscribe forte-users' as the body of the message.
Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/>
Nondeposit investment products are not insured by the FDIC, are
not deposits or other obligations of or guaranteed by U.S. Bank
National Association or its affiliates, and involve investment
risks, including possible loss of the principal amount invested.
Past performance does not guarantee future results. We consider
our sources reliable. Accuracy and completeness are not guaranteed.
Information is subject to change. Transactional details should not
be relied on for tax purposes and do not supersede normal trade
confirmations or statements. Messaging outside U.S. jurisdictions
from U.S. Bancorp Piper Jaffray to non-institutional parties is not
intended for solicitation purposes.
Electronic mail sent through the Internet is not secure. We will
not accept time-sensitive, action-oriented messages, transaction
orders, fund transfer instructions or check stop payments
electronically.
If you are not the intended recipient, notify the Sender. This
information is intended only for the person named above and for
the purposes indicated. Do not distribute this message without
written consent of the author. Non-business opinions may not
reflect opinions of U.S. Bancorp Piper Jaffray and its affiliates.
U.S. Bancorp Piper Jaffray and its affiliates reserve the right to
monitor all e-mail.
Securities products and services are offered through
U.S. Bancorp Piper Jaffray Inc., member SIPC and NYSE, Inc.,
a subsidiary of U.S. Bancorp.
To unsubscribe, email '[email protected]' with
'unsubscribe forte-users' as the body of the message.
Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/> -
Attempting to update itunes, received system error" Program can't start because MSVCR80.dll is missing from computer, try reinstalling the program to fix the problem. Question, I can't access Itunes to backup library, how do I reinstall without loosing music library?
It doesn't matter and doing a manual install will not fix the problem either. I'm looking for a solution but no luck yet. I think Apple has given us a bad update.
-
Some problems and questions using OWB
For Igor or anyone who can help me :-)
Hello Igor,
Thanks for all your help concerning my mapping deployment problem! Now its working better ;-)
I used the OWB Runtime Assistant to create a new runtime target schema and i use the owner of this schema as user while logging to OWB.
Now i can create and deploy without problems mappings, tables, functions, procedures, packages, dimensions, views, materialized views, process flows (i have installed the Oracle Workflow Client 2.6.2.0.0 with OWF builder and OWF mailer ).
However I have still some problems and questions :-)
a) After deploying a mapping or process flow i can execute them from OWB Deployment Manager. How can i schedule the execution of a deployed precess without using OWBDM ? (I want to execute a process every day to perform ETL).
b) I think i have a problem deploying cubes. I create a cube in OWB, the validation is OK, the deploment succeds, but if i look with OEMC in the tree in the Warehouse OLAP section no cube is created. Only the fact tabe is created. If i look to the scripts from the Pre Deployment generation results i found DDLs only for TABLE, INDEX, UNIQUE KEY, FOREIGN KEY and ANALYZE object types, meanwhile during a dimension deployment i found also a DDL for the DIMENSION type object. WHY ?
c) If I look in the procedures of the new created OWB Runtime Target Schema I found 3 procedures which are in error and when I try to compile them I receive the following error messages :
- procedure WB_OLAP_LOAD_CUBE
PLS-00201: identifier 'DBMS_AWM.CREATE_AWCUBELOAD_SPEC' must be declared
- procedure WB_OLAP_LOAD_DIMENSION
PLS-00201: identifier 'DBMS_AWM.CREATE_AWDIMLOAD_SPEC' must be declared
- procedure WB_OLAP_LOAD_DIMENSION_GENUK
PLS-00201: identifier 'DBMS_AWM.CREATE_AWDIMLOAD_SPEC' must be declared
How can solve this problem? Is there any link with the fact that the cube is not generated?
d) When I first acces the deployed DIM in the OEMC tree I receive a message saying that the dimension does not have complete metadata as needed for use by Oracle OLAP services (because is created either in an earlier version of Oracle database or it was created by an an other application than OEMC) and OEMC automatically generates the default needed metadata. Is this normal ?
I work in an environment with
- Oracle 9i Database 9.2.0.1.0
- Oracle 9i Client 9.2.0.1.0
- Oracle 9i Warehouse Builder Products 9.2.0.2.8
Best Regards:
Vlad
PS Sorry for my poor English ;-)Answered in your "Getting RPE-01008 when deploying mappings" post.
Regards:
Igor -
First problem...
SQL root will not access all databases...
If I try to access al databases using SQL Administrator the connection is refused even if I use root.
all databases are accessable va individual username and password..
Tried changing root password with GUI but makes no difference...
Second SQL problem...
10.4.11 server failed all raid volumes so corrupted no rescue was possible on any volume reinstall failed as well...
Have rebuilt the server using 10.5.6 I will have to manually import the SQL databases from the old server... what do I do ??? I cannot boot the old server so cannot do an SQL export or anything...
Thanks...Hi Jun,
Can i contribute a little for ur 2nd problem.
This error is coz, If u are using a filter against a File "data store" u can't test it, only against RDBMS query will be tested at data store level.
Well, for using that filter and make sure its working, drag and drop the source file in the interface (u can get the filter) and make it to execute on STAGING.
Thanks,
Guru -
Hello,
I have a small SQL problem...
I am designing an online bank using servlets for a university project and it allows customers to view their statements. They select which of their account numbers they want to view the statement for and the start and end date of the statement.
The problem lies with the dates. Here is the SQL:
SELECT date, details, amount, balance
FROM HISTORY
WHERE bankaccnumber=13494925 And date>=1/1/01 And date<=31/1/01;
All of the books I have looked at show dates in '1/1/01' format but whenever I try it this way I get a 'Data type mismatch in criteria expression' error (the 'date' field in the Database IS a Date type).
Although, whenever I run the query in Access and prompt the user to enter the start and end date, it works fine.
I have spoken to a few people and no-one seems to know why it is not working.
Any ideas???
ThanksIf your database is MS Access and you don't expect to switch to something else, then write this:
SELECT date, details, amount, balance
FROM HISTORY
WHERE bankaccnumber=13494925 And [date]>=#1/1/01# And [date]<=#1/31/01#
Note that you MUST format your dates as MM/DD/YY and not as DD/MM/YY, that's an Access rule, and that you will probably have to "quote" your column name "date", which I think is a reserved word in SQL and hence a bad choice for column name.
Personally I always use PreparedStatements. That way my SQL would look like this:
SELECT date, details, amount, balance
FROM HISTORY
WHERE bankaccnumber=13494925 And date>=? And date<=?
and I would use the setDate() method to fill in the parameters. Since this method uses a Date as a parameter, I don't need to fight with date formats, the JDBC driver handles that for me. -
I have some problems and questions about my MSI MEGA PC 180 system...
One problem is that MSI live monitor only works one time after every new installation then is just say "The URL is invalid" every other time I try to search for updates.
One problem is that one of the fans doesn't turn off when I turn of the computer and the only way to get i to turn off is to turn on the hifi mode and turn it off then the fan stops. And some times the fan can start after a while when the computer has been turned off.
There are two fans for the cooling of the CPU but PCALERT only shows the speed of one of them.. why? according to the manual one of the is called CPU fan and the other one is called sysfan but only CPU fan showes i PCALERT.
Are there no other way to control the Tv other than with the Home Teather system than I find way to slow if you use 1280x1024 resolution on the screen like I do. And are there no way to sort and remove channels in home teather? As i is now I can't move the channels in the order I want and I can't remover channels that the auto search thaught was channels but aren't?
An other thing that I find annoying is that the fullscreen mode of home teather doens't cover all off the screen it doesn't hide the systray and leaves a small but annoying kolumn to the right that showes the backgrund and that is very annoying to watch tv if you have a light backgrund because the kolumn are so bright.Welcome Kabbo,
I see you agree that MC III is far from perfect. Perhaps you can try the combination of Media Portal and Ir2Key. Just read some of the other posts including "WinIRX.ocx internals/usage" by ddookie. Another possibility is to try Dscaler, but this program is only for watching TV.
Regarding the processor fans: its normal that only one of the two shows up in PcAlert; when you look closely to both fans you'll see that one has only a two-wired connection.
The problem of a fan not shutting down is new to me, I suppose you have checked the connections to your mobo?
Greetz,
JaDi -
SQL Server Problems and Questions from an SQL dummy
I am an SQL Dummy!
In the old 2008 version of SQL I had to run a script to fix a rounding error in my Microsoft Accounting software (no longer supported) I think I have version 10 now?
SQL FIX for Fiscal Year won't close
Need to use Sql Management Studio (as oppose to more obscure osql.exe)
to run sql script
b) Use Sql Management Studio to execute script below:
SELECT *
FROM dbo.CashPostingTable
WHERE (amountcredit <> amountCreditCompanyCurrency OR amountDebit <>
amountDebitCompanyCurrency) AND exchangeRate=100
If you get any rows/data back, proceed to step c), if no result, a more
serious problem - good lucks or buy help.
c) Use Sql Management Studio to execute script below:
UPDATE cashpostingtable
SET amountCreditCompanyCurrency = amountCredit,
amountDebitCompanyCurrency = amountDebit,
companyAmountRemainder = accountAmountRemainder
WHERE (amountcredit <> amountCreditCompanyCurrency OR amountDebit <>
amountDebitCompanyCurrency) AND exchangeRate=100
Management Studio no longer works. Is there a way to do the same thing in the version I have?
Thank you,
DeanI am an SQL Dummy!
In the old 2008 version of SQL I had to run a script to fix a rounding error in my Microsoft Accounting software (no longer supported) I think I have version 10 now?
SQL FIX for Fiscal Year won't close
Need to use Sql Management Studio (as oppose to more obscure osql.exe)
to run sql script
b) Use Sql Management Studio to execute script below:
SELECT *
FROM dbo.CashPostingTable
WHERE (amountcredit <> amountCreditCompanyCurrency OR amountDebit <>
amountDebitCompanyCurrency) AND exchangeRate=100
If you get any rows/data back, proceed to step c), if no result, a more
serious problem - good lucks or buy help.
c) Use Sql Management Studio to execute script below:
UPDATE cashpostingtable
SET amountCreditCompanyCurrency = amountCredit,
amountDebitCompanyCurrency = amountDebit,
companyAmountRemainder = accountAmountRemainder
WHERE (amountcredit <> amountCreditCompanyCurrency OR amountDebit <>
amountDebitCompanyCurrency) AND exchangeRate=100
Management Studio no longer works. Is there a way to do the same thing in the version I have?
Thank you,
Dean -
hello all,
PROBLEM :
I followed this thread Copying data from one field to another on a form
but unfortunately..encountered with d following error...
Any PL/SQL coding is throwing such errors on my portal..
I have to install any additional tools or configure something..( I done executed the provsyns.sql for myschema)
Someone please suggest me..
ERROR :
Internal error (WWC-00006)
An unexpected error occurred: ORA-01001: invalid cursor (WWV-16016)
Error displaying form : ORA-01001: invalid cursor (WWV-16408)
Error running user PL/SQL code: ORA-01001: invalid cursor (WWV-16403)
ORA-06550: line 5, column 7:
PLS-00201: identifier 'P_SESSION.GET_VALUE_AS_VARCHAR2' must be declared
ORA-06550: line 5, column 1:
PL/SQL: Statement ignored
ORA-06550: line 8, column 9:
PLS-00201: identifier 'P_SESSION.GET_VALUE_AS_VARCHAR2' must be declared
ORA-06550: line 8, column 1:
PL/SQL: Statement ignored
ORA-06550: line 11, column 1:
PLS-00201: identifier 'P_SESSION.SET_VALUE' must be declared
ORA-06550: line 11, column 1:
PL/SQL: Statement ignored
ORA-06550: line 15, column 1:
PLS-00201: identifi (WWV-11230)
Failed to parse as PORTAL_PUBLIC - BEGIN declare
id varchar2(20);
name varchar2(20);
begin
id := p_session.get_value_as_VARCHAR2(
p_block_name => 'DEFAULT',
p_attribute_name => 'EMP_ID');
name := p_session.get_value_as_VARCHAR2(
p_block_name => 'DEFAULT',
p_attribute_name => 'EMP_NAME');
p_session.set_value(
p_block_name => 'DEFAULT',
p_attribute_name => 'ID',
p_value => id);
p_session.set_value(
p_block_name => 'DEFAULT',
p_attribute_name => 'NAME',
p_value => name);
end; END; (WWV-08300)
The preference path does not exist: ORACLE.WEBVIEW.PARAMETERS.1668713167 (WWC-51000)
Many Thanks In Advance :-)hi Pappu
if you have used the same exact code as given in the message you have mentioned, then please correct one variable's name. the reply I gave in that thread has a typo. in suggesting a solution to that question, I had tried it with a different set of variables on my system and in replying back, i mistakenly left one such variable in that thread.
try it and see if you still get errors.
AMN
declare
v_address1 varchar2(20);
begin
v_address1 := p_session.get_value_as_VARCHAR2(
p_block_name => 'DEFAULT',
p_attribute_name => 'A_ADDRESS1');
p_session.set_value(
p_block_name => 'DEFAULT',
p_attribute_name => 'A_LOCATION1',
p_value => v_address1);
end; -
Sql Problems, Same Field Names In Multiple Mysql Tables?
I have a keyword search that searches multiple DB tables for thumbnail images using UNION ALL. I have two pages, results.php, and view.php. My goal is to able to click a thumbnail image on results.php and be directed to a larger version of that same image on view.php. The problem is each image in all my tables uses the field name "id" so when I click a thumbnail on results.php I get two different images with the same id from different tables. I tried changing the id's to different names, but when it was time to pass url parameters I can only choose 1 value. (if you can choose more than 1 I don't know how). So my question is why are my id's from different tables being grouped together, and how can I change this?
Image Results Page (which works perfect):
SELECT *
FROM table1
WHERE keyword LIKE %colname% OR id LIKE %colname%
UNION ALL
SELECT *
FROM table2
WHERE keyword LIKE %colname% OR id LIKE %colname%
View Image Page (having problems here):
SELECT *
FROM table1
WHERE id = colname
UNION ALL
FROM table2
WHERE id = colnameYes, that is going to be a problem - and it's just the beginning of your problems when you do not normalize your data. Your data model is not correct. You should not be storing similar data in 15 tables - it's a really big mistake.
To solve your current problem you would need to include a table identifier in the query results in the Image results page, and pass that to the view page and then use PHP to dynamically create the SQL with the correct table....ugh! -
I'm having a really strange problem and I hope someone here can explain why this is happening:
I run this query, it should only return segment2 if the first character is alpha and the 2nd character is number.
SELECT
gcc.segment2
,SUBSTR(apps.gl_flexfields_pkg.get_description_sql( gcc.chart_of_accounts_id,2,gcc.segment2),1,40) segment2_desc
FROM gl_code_combinations gcc
WHERE (REGEXP_LIKE(substr(segment2, 1,1), '^[a-zA-Z]*$') AND
SUBSTR(segment2, 2,1) NOT LIKE '%[^a-zA-Z]%');
So it returns the correct results segment along with the description:
X01234
X12345
X54321
etc.
Run same query with enabled _flag added to where clause and expressions don’t work:
SELECT
gcc.segment2
,SUBSTR(apps.gl_flexfields_pkg.get_description_sql( gcc.chart_of_accounts_id,2,gcc.segment2),1,40) segment2_desc
FROM gl_code_combinations gcc
WHERE (REGEXP_LIKE(substr(segment2, 1,1), '^[a-zA-Z]*$') AND
SUBSTR(segment2, 2,1) NOT LIKE '%[^a-zA-Z]%')
AND gcc.enabled_flag = 'Y';
Returns a list of just one segment value with it's description:
DT101
DT101
etc.
Why is this happening? I'm intending to use this query in a value set. Just trying it out in Toad and SQL Developer right now.Hi,
MinnieB wrote:
I'm having a really strange problem and I hope someone here can explain why this is happening:
I run this query, it should only return segment2 if the first character is alpha and the 2nd character is number.
SELECT
gcc.segment2
,SUBSTR(apps.gl_flexfields_pkg.get_description_sql( gcc.chart_of_accounts_id,2,gcc.segment2),1,40) segment2_desc
FROM gl_code_combinations gcc
WHERE (REGEXP_LIKE(substr(segment2, 1,1), '^[a-zA-Z]*$') AND
SUBSTR(segment2, 2,1) NOT LIKE '%[^a-zA-Z]%');
So it returns the correct results segment along with the description:
X01234
X12345
X54321
etc.
Run same query with enabled _flag added to where clause and expressions don’t work:
SELECT
gcc.segment2
,SUBSTR(apps.gl_flexfields_pkg.get_description_sql( gcc.chart_of_accounts_id,2,gcc.segment2),1,40) segment2_desc
FROM gl_code_combinations gcc
WHERE (REGEXP_LIKE(substr(segment2, 1,1), '^[a-zA-Z]*$') AND
SUBSTR(segment2, 2,1) NOT LIKE '%[^a-zA-Z]%')
AND gcc.enabled_flag = 'Y';
Returns a list of just one segment value with it's description:
DT101
DT101
etc.
Why is this happening? The value you're displaying is not the same as the value used in the regular expressions. The function get_description might return 'DT101' when its 3rd argument (segement2) is something like 'T101'.
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, CREATE FUNCTION statements for any functions needed, and also post the results you want from that data.
Feel free to simplify the problem. It looks like this whol;e question hinges on gcc.enabled_flag, gcc.segment2 and the value that get_description returns when that segment2 is an argument. In that case, you can post CREATE TABLE and INSERT statements for a single table with 3 columns: enabled_flag, segment2, and f (which is the same as your function results).
Explain, using specific examples, how you get those results from that data.
Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
See the forum FAQ {message:id=9360002}
Edited by: Frank Kulash on Mar 1, 2013 11:19 AM
Apparantly, I mis-read the problem. The reply above is appropriate for a question that makes sense, not what was posted. My apologies. -
PL/SQL :: Problem With Large Number Computation.
Greetings Experts,
I am relatively new to Oracle-DB. And I have a question regarding PL/SQL. I was trying to find the factorial of a number 100 as this is the most common programming problem for the beginners. But when I tried to execute the same, I was getting weird result(~) instead of actual value, i. e. 100!. I would highly appreciate if you experts can guide me in this regard. I have posted the program herewith for your reference.
SQL> DECLARE
2 X NUMBER := 100;
3 INDX NUMBER := 1;
4 BEGIN
5 INDX := X;
6 WHILE X > 1
7 LOOP
8 X := X - 1;
9 INDX := INDX * X;
10 END LOOP;
11 DBMS_OUTPUT.PUT_LINE('The Factorial of 100 is : '
12 || INDX || '.');
13 EXCEPTION
14 WHEN OTHERS THEN
15 RAISE_APPLICATION_ERROR(-20156,SUBSTR(SQLERRM,1,500));
16 END;
17 /
The Factorial of 100 is : ~.
PL/SQL procedure successfully completed.
TIA.
Hex.This is PL/SQL and works up to 1463:
SQL> CREATE OR REPLACE FUNCTION factorial(
2 pNumber IN NUMBER)
3 RETURN VARCHAR2
4 IS
5 f VARCHAR2(32767);
6
7 FUNCTION multiply(
8 pX IN VARCHAR2,
9 pY IN VARCHAR2)
10 RETURN VARCHAR2
11 IS
12 xManLength PLS_INTEGER;
13 yManLength PLS_INTEGER;
14 BEGIN
15 xManLength := LENGTH(RTRIM(pX, '0'));
16 yManLength := LENGTH(RTRIM(pY, '0'));
17 RETURN TO_CHAR(TO_NUMBER(SUBSTR(pX, 1, xManLength)) * TO_NUMBER(SUBSTR(pY, 1, yManLength)))
18 || RPAD('0', LENGTH(pX) - xManLength + LENGTH(pY) - yManLength, '0');
19 END multiply;
20 BEGIN
21 f := 1;
22
23 FOR n IN 1 .. pNumber LOOP
24 f := multiply(f, n);
25 END LOOP;
26
27 RETURN f;
28 END factorial;
29 /
Funktion wurde erstellt.
SQL>
SQL> SELECT 1463, factorial(1463) AS fact
2 FROM DUAL;
1463
FACT
1463
229804713272032214845417447319796313384000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000 -
Hey Ppl,
Ok i have a problem getting my Insert Into SQL to work.... i've created a small program that inputs information directly into the database... but even then i get a syntax error with my insert into statement...
if you guyz can look at it and tell me where my problem lies... it'll be Cool...
public class HAddSQL {
public static void main (String args []){
String url = "jdbc:odbc:PP";
Connection con;
Statement stmt;
String query = "select * from HarvestFile";
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
catch(java.lang.ClassNotFoundException e){
System.err.print("ClassNotFoundException: ");
System.err.print("/n"+e.getMessage());
try{
con = DriverManager.getConnection(url);
stmt = con.createStatement();
stmt.executeUpdate("insert into HarevestFile" +
"values('MG002', 'NS001', 03/24/2001, 250, 0, 95.40, 'Samad', 'CRAZY')");
ResultSet rs = stmt.executeQuery(query);
System.out.println("Test For This SQL Experiment");
while(rs.next()){
String s = rs.getString("TreeID");
String a = rs.getString("SegmentCode");
System.out.println(s + " " + a);
stmt.close();
con.close();
catch(SQLException ex){
System.err.println("SQLException: " + ex.getMessage());
I'm using Microsoft Access btw...
ok... another question... does anyone know how to save the date a document was saved in a database... like for instance.... if i had a interface and i was to fill in the information.... when i click submit... the database captures the date that it was submitted???
I'm a newbie in this so you'll have to go easy on me ok?
Thanx ppl...
~John~ok hi partha....
thanx for keeping in touch till now...
ok this is a small portion of what i have done to my java.sql.* it's part of an interface... whereby when the user enters the values in a textfield... the interface sends it to the database.... ok here it is
con = DriverManager.getConnection(url);
java.sql.Date date = new java.sql.Date(System.currentTimeMillis());
stmt = con.createStatement();
stmt.executeUpdate("insert into HarvestFile (" +
"TreeID, SegmentCode, NumberOfTrees, NumberRemaining," +
"Revenue, ForestOfficer, Comments" +
") values ('" +
tf1.getText() + "','" +
tf0.getText() + "','" +
tf5.getText() + "','" +
tf7.getText() + "','" +
tf6.getText() + "','" +
tf8.getText() + "','" +
tf9.getText() + "')");
ResultSet rs = stmt.executeQuery(query);
System.out.println("Display Success Results:");
while(rs.next()){
String s = rs.getString("TreeID");
String a = rs.getString("SegmentCode");
System.out.println(s + " " + a);
stmt.close();
ok... see what you can make of this....
i've tried it out... and well... i just can't get the date to appear.... i'll keep trying anyways... .
Do send me your ideas... .
Thanx....
Regards
John -
SQL - Analytical Query Question
Hi All,
I have a requirement for which I am trying to generate the output and I am not able to come up with good logic to solve this issue. I have been trying to solve this for some time now and am not able to figure out how.
I have posted a similar kind of post some time back but this is different to the original one and little more complex than my previous question. I have listed below the script to create a table and insert data.
DROP TABLE ITEMTABLE
CREATE TABLE ITEMTABLE
ITEMTABLEID1 NUMBER(9) NOT NULL,
ITEMTABLEID2 NUMBER(9) NOT NULL,
PARENTTABLEID NUMBER(9),
PARENTINFO VARCHAR2(20),
CONSTRAINT ITEMTABLE_PK PRIMARY KEY (ITEMTABLEID1,ITEMTABLEID2)
Insert into ITEMTABLE values (19217,10245,19216,'PARENTINFO-1');
Insert into ITEMTABLE values (19217,10315,19216,'PARENTINFO-2' );
Insert into ITEMTABLE values (19217,10336,19216,'PARENTINFO-2' );
DROP TABLE FINANCE
CREATE TABLE FINANCE
FINANCEKEY NUMBER(9) NOT NULL,
PARENTID1 NUMBER(9) NOT NULL,
PARENTID2 NUMBER(9) NOT NULL,
CONSTRAINT FINANCE_PK PRIMARY KEY (FINANCEKEY)
Insert into FINANCE values (8332, 19217,10245);
Insert into FINANCE values (8404, 19217, 10315);
Insert into FINANCE values (8425, 19217, 10336);
DROP TABLE ACCT
CREATE TABLE ACCT
ACCTKEY NUMBER(9) NOT NULL,
FINANCEKEY NUMBER(9),
FLAG VARCHAR2(1),
SOURCEKEY NUMBER(9),
CONSTRAINT ACCT_PK PRIMARY KEY (ACCTKEY)
Insert into ACCT values (9874, 8332, 'N',0);
Insert into ACCT values (9875, 8332, 'N',0 );
Insert into ACCT values (9982, 8404, 'Y', 9874);
Insert into ACCT values (9983, 8404, 'Y', 9875);
Insert into ACCT values (10008, 8425, 'N', 9982);
Insert into ACCT values (10009, 8425, 'Y', 9983);
SQL> With tempacct1 as
2 (Select I.ITEMTABLEID1,I.ITEMTABLEID2, AC.SOURCEKEY, NVL(AC.FLAG,'N') AS FLAG, AC.ACCTKEY
3 FROM ITEMTABLE I,FINANCE F,ACCT AC
4 where I.ITEMTABLEID1 = F.PARENTID1
5 and I.ITEMTABLEID2 = F.PARENTID2
6 and F.FINANCEKEY = AC.FINANCEKEY
7 and I.PARENTTABLEID = 19216
8 ORDER BY acctkey ASC
9 )
10 SELECT ITEMTABLEID1,ITEMTABLEID2,acctkey, flag ,SOURCEKEY
11 FROM tempacct1;
ITEMTABLEID1 ITEMTABLEID2 ACCTKEY F SOURCEKEY
19217 10245 9874 N 0
19217 10245 9875 N 0
19217 10315 9982 Y 9874
19217 10315 9983 Y 9875
19217 10336 10008 N 9982
19217 10336 10009 Y 9983
6 rows selected.
Desired Output -
ITEMTABLEID1 ITEMTABLEID2 ACCTKEY F SOURCEKEY
19217 10336 10008 N 9982
19217 10336 10009 Y 9983The solution by Frank for my previous post few weeks back looks like this :-
SQL> SELECT sourcekey
2 , flag
3 , acctkey
4 FROM (
5 SELECT ac.sourcekey
6 , NVL (ac.flag, 'N') AS flag
7 , ac.acctkey
8 , RANK () OVER ( PARTITION BY CASE
9 WHEN sourcekey = 0
10 THEN acctkey
11 ELSE sourcekey
12 END
13 ORDER BY CASE
14 WHEN ac.flag = 'Y'
15 THEN 1
16 ELSE 2
17 END
18 , SIGN (sourcekey)
19 ) AS rnk
20 FROM itemtable i
21 , finance f
22 , acct ac
23 WHERE i.itemtableid1 = f.parentid1
24 AND i.itemtableid2 = f.parentid2
25 AND f.financekey = ac.financekey
26 AND i.parenttableid = 19216
27 )
28 WHERE rnk = 1;
SOURCEKEY F ACCTKEY
9874 Y 9982 -- Needs to be removed
9875 Y 9983 -- Needs to be removed
9982 N 10008
9983 Y 10009
Output Desired would be
ITEMTABLEID1 ITEMTABLEID2 ACCTKEY F SOURCEKEY
19217 10336 10008 N 9982
19217 10336 10009 Y 9983
SQL> The slight change to the requirement is when we have sourcekey that is same as acctkey then only display the row which has max acctkey. So in this case, the last two row have a sourcekey of 9982, 9983 which is equal to acctkey of first two rows. So, we look for Max(Acctkey) which would be 10008 and 10009 and only display those.
This logic needs to be added on top of the existing logic. So I am not sure how it could be done.
I would really appreciate any help.
SQL> select * from v$version;
BANNER
Oracle Database 10g Release 10.2.0.4.0 - 64bit Production
PL/SQL Release 10.2.0.4.0 - Production
CORE 10.2.0.4.0 Production
TNS for Linux: Version 10.2.0.4.0 - Production
NLSRTL Version 10.2.0.4.0 - ProductionEdited by: ARIZ on Jun 16, 2010 7:56 PMHi,
This gets the right results from your sample data.
SELECT ac.sourcekey
, NVL (ac.flag, 'N') AS flag
, ac.acctkey
FROM itemtable i
, finance f
, acct ac
WHERE i.itemtableid1 = f.parentid1
AND i.itemtableid2 = f.parentid2
AND f.financekey = ac.financekey
AND i.parenttableid = 19216
AND ac.acctkey NOT IN ( SELECT sourcekey
FROM acct
WHERE sourcekey IS NOT NULL -- If needed
; I'm a little uncertain of your requirements, so I'm not sure how it will work on your real data.
At least in this new version of the problem, it looks like rows can be chained together, where the sourcekey of one row is the acctkey of the next row. If you want only the first row in each such chain, just look for the ones where the acctkey does not relate back to any sourcekey.
NOT IN is never TRUE if the subquery returns any NULLs. Unless sourcekey has a NOT NULL constraint, you'd better check for it in the NOT IN sub-query. -
Please help me with PL/SQL problem
Hi to all
This is my problem. I have a database with several tables. I will mention just some important for this problem. I have a table called Invoice, where I have following atributes
sifrac number(9) not null primary key,
datrac date default sysdate,
sifkup number(5),
sifprod number(5) not null,
ukcena number(5,2)
Then I have table called History of customer where I have
constraint pk_istkup primary key(sifrac,sifkup),
sifrac number(9) constraint fk_sifrac2 references racun(sifrac),
sifkup number(5) constraint fk_sifkup3 references kupac(sifkup) this is primary key in a table customer,
datrac date default sysdate,
ukcena number(5,2) this is total price of purchased stuff per one invoice.
What I would like to do now is make a trigger before insert or update table Invoice which check table History of customer and make a calculation of all total prices per one customer and if that customer made a purchase which is more than 1000 dollars then it have to make a calculation of total price*discount percent.How can I do that.
Thanks to all in advanceBilly Verreynne wrote:
LKBrwn_DBA wrote:
This type of functionality (a business rule to compute discount) would normally be added at the application level and not in a trigger. Why? Does business rule code need Java to be expressed correctly? Does Java (or whatever application layer language) used provide a better set of instructions for doing business rules than PL/SQL? Is business code written using a special keyboard and a pretty font?
And what happens when new system feeds invoice data for new department/division directly into the database, bypassing the app layer? What happens to that app layer business logic now?
It is a fallacy that business rules and logic needs to reside in a separate layer as that is somehow better. I disagree. LKBrwn_DBA didn't mention Java as an application layer. And he was not strict about it. So yes it is possible to use a trigger. But business logic tends to be changed fequently. So the rules for the logic might change. I would implement such logic using a pacakged pl/sql api. Triggers I would use for data validations and checks that are less likely to be changed.
As always it depends. But the general advice to have a certain level of business logic (e.g. apis) and another level of data integration and consitency layer (e.g. constraints and triggers) is a good advice.
As for bypassing the application layer. If an new system is able to do that, it can wreck even more havoc. A good anti mechanism is to expose only the APIs layer in a separate schema. The new system will have access to the schema and to the packages that are specified there. But it won't have direct dml to the tables.
Main question for me would be: Is that a business rule or is it a data integration rule (e.g. keep redundant data in different tables harmonized). This influences where the logic will be implemented.
Edited by: Sven W. on Oct 2, 2009 8:59 AM
Maybe you are looking for
-
HT2479 I'm trying to extract a photo clip from my video. How do I do that?
I just took a video of my daughter's new wine and cheese shop. She loved it and wanted a picture of her that is in the movie. Can I extract a photo clip from the movie? I can't figure out how to do it and would love some help. Thanks.
-
I don't know what more I can provide until maybe it pops up again....which I'm sure it will.
-
Executing "at" command of UNIX through JSP
Friends, 1. "at" command in UNIX execute Unix command at a scheduled time. 2. For each user there will be a table maintained internally which can be accessed by "at" with "-l" argument. 3. A mail will be sent to the owner with the output of the comma
-
Multi currencies in oracle hrms
Hi , I have one employee and he is from India and he is working in USA. and We have pay him 50% in India Rupees and 50% in Dollars and his total salary is 1,00,000 Per Month. Can any one send me the setup for the Multi currencies to my mail id : [ema
-
Updated to FF 18.0.2, now FF crashes at startup
I updated FF to 18.0.2. Immediately after update FF crashes at startup. FF will run in safe mode. Crash ID: bp-f138d304-0040-4ac9-b51e-ab8c12130206 Please advise. Thanks.