Need help with SQL*PLUS!
I have just downloaded Oracle SQL*PLUS 9.2.0.1.0, but I am not able to use it because I do not know the "password", "user name" and "host string". Can anybody please help me with this.
Thanks in advance,
Flo
The username & password are your database username & password. If you don't know these, you'll have to contact your DBA to find out.
The host string is the alias you used when you configured TNS on your machine. Most commonly, this is done by editing the tnsnames.ora file or by using Net8 Easy Config.
Justin
Distributed Database Consulting, Inc.
www.ddbcinc.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,
NickIt 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. -
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 -
i install in my computer the oracle9i
my problem is that : i can login to sql plus
althoge i was tring all the passwords that i know
scott/tiger
sys/change_on_install
system/manager and the result is allways the same
ora-12560 error
how can i solve that problem?
did i missed somthing during the installation?Thank you to EVERYONE!!
I have been searching every possible forum to find out how to install/run SQL *Plus on a home computer without a server/network to work within. As most just learning, I could not figure out how to get past the SQL Plus Username/Password/Host String logon.
After much trial and error, I got through and I hope this helps a lot of people just starting out.
I used 'SYSTEM' as my username and my password created on install.
When installing I created a database and fixed the password so my default password was the password I created on install.
As long as I had those two fields filled in, I could leave the Host String blank and I could still get into the SQL Plus workspace.
Since I also created a database on install, I found that I could also use the name I gave the installed database (I didn't leave the default database name so I do not remember what the default name was, but I think the default password was 'manager' for those who were not tempted to change it).
Worst case scenario if you forgot your database name given during install, you can do a search for all of your .ora files (usually in the drive you installed Oracle on). Open the tnsnames.ora file in Notepad and you can see which database names are available on your system. The path to my file was:
D:\oracle\product\10.2.0\db_1\network\admin\tnsnames.ora
You want the SERVICE_NAME = 'databasename'
I hope this reduced someone's stress...and thanks for all the helpful hints on these threads...they led me to the final outcome!!
In the end, I tried a lot of other combinations for the username/host strings with plenty of errors. You would think this information would be on page one of every Oracle install!! Or maybe it is and I am just a bit slow. : )
Thanks again to all that posted with this initial question (years ago)...
Brian Reeves
Oracle Student -
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 PrusinskiHi 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
) -
Need help with SQL retrieval for previous month till current date
Hi ,
Need help generating statistics from previous month from date of enquiry till current date of enquiry.
and have to display it according to date.
Date of enquiry : 03/02/2012
Application Type| 01/01/2012 | 02/01/2012 | 03/01/2012 |...... | 31/01/2012 | 01/02/2012 | 02/02/2012 | 03/02/2012 |
sample1 20 30 40
sample 2 40 40 50
sample 3 50 30 30
Hope you guys can help me with this.
RegardsHi,
932472 wrote:
Scenario
1)If i run the query at 12 pm on 03/2/2012. the result i will have to display till the current day.
2)displaying the count of the application made based on the date.
Application type 01012012 | 02012012 | 03012012 | ..... 01022012| 02022012|03022012
sample 1 30 40 50 44 30
sample 2 35 45 55
sample 3 36 45 55Explain how you get those results from the sample data you posted.
It would help a lot if you posted the results in \ tags, as described in the forum FAQ. {message{id=9360002}
SELECT application_type as Application_type
, COUNT (CASE WHEN created_dt = sysdate-3 THEN 1 END) AS 01012012 (should be getting dynamically)
, COUNT (CASE WHEN created_dt = sysdate-4 THEN 1 END) AS 02022012
, COUNT (CASE WHEN created_dt = sysdate-5 THEN 1 END) AS 03022012
, COUNT (CASE WHEN created_dt = sysdate-6 THEN 1 END) AS 04022012
FROM table_1
GROUP BY application_type
ORDER BY application_typeThat's the bais idea.
You can simplify it a little by factoring out the date differences:WITH got_d AS
SELECT qty
, TRUNC ( dt
- ADD_MONTHS ( TRUNC (SYSDATE, 'MON')
, -1
) AS d
FROM table1
WHERE dt >= ADD_MONTHS ( TRUNC (SYSDATE, 'MON')
, -1
AND dt < TRUNC (SYSDATE) + 1
SELECT SUM (CASE WHEN d = 1 THEN qty END) AS day_1
, SUM (CASE WHEN d = 2 THEN qty END) AS day_2
, SUM (CASE WHEN d = 62 THEN qty END) AS day_62
FROM got_d
See the links I mentioned earlier for getting exactly the right number of columns, and dynamic column aliases. -
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 descHi 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 ; -
Need Help With SQL GROUP BY and DISTINCT
I am working on a project and need to display the total of each order based on the order id. For instance I want to display the order id, customer id, order date, and then the extension price (ol_quantity * inv_price).
I would then like a total displayed for order # 1 and then move on to order #2.
Here is my SQL code :
SELECT DISTINCT orders.o_id, customer.c_id, inv_price * ol_quantity
FROM orders, customer, inventory, order_line
GROUP BY orders.o_id, customer.c_id, inv_price, ol_quantity
ORDER BY orders.o_id;
When my code is run it displays the order id, customer id and inv_price * quantity (extension price) but no order total for the order number and a new group is not started when a new order number is started....they are all clumped together.
Any help is greatly appreciated!!Hi,
user12036843 wrote:
I am working on a project and need to display the total of each order based on the order id. For instance I want to display the order id, customer id, order date, and then the extension price (ol_quantity * inv_price).
I would then like a total displayed for order # 1 and then move on to order #2.
Here is my SQL code :
SELECT DISTINCT orders.o_id, customer.c_id, inv_price * ol_quantity
FROM orders, customer, inventory, order_line
GROUP BY orders.o_id, customer.c_id, inv_price, ol_quantity
ORDER BY orders.o_id;
When my code is run it displays the order id, customer id and inv_price * quantity (extension price) but no order total for the order number and a new group is not started when a new order number is started....they are all clumped together.
Any help is greatly appreciated!!Sorry, it's unclear what you want.
Whenever you post a question, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and the results you want from that data.
Explain, using specific examples, how you get those results from that data.
Always say what version of Oracle you're using.
Do you want the output to contain one row for each row in the table, plus an extra row for each distinct order, showing something about the order as a whole (e.g., total inv_price or average extension_price)? If so, you need GROUP BY ROLLUP or GROUP BY GROUPING SETS .
If you want one row of output for each row of the table, but you want to include something that reflects the group as a whole (again, e.g, total inv_prive or average extension_pcie), then you can us analytic functions. (Most of the aggregate functions, such as SUM and AVG have analytic counterparts that can get the same results without collapsing the result set down to one row per group.)
Here's an example of how to use GROUP BY GROUPING SETS.
Way we're interested in employees' salary and commission from the scott.emp table:
SELECT deptno
, ename
, sal
, comm
FROM scott.emp
ORDER BY deptno
, ename
;Output:
` DEPTNO ENAME SAL COMM
10 CLARK 2450
10 KING 5000
10 MILLER 1300
20 ADAMS 1100
20 FORD 3000
20 JONES 2975
20 SCOTT 3000
20 SMITH 800
30 ALLEN 1600 300
30 BLAKE 2850
30 JAMES 950
30 MARTIN 1250 1400
30 TURNER 1500 0
30 WARD 1250 500Now say we want to add the total income (sal + comm, or just sal if there is no comm) to each row, and also to add a row for each department showing the total sal, comm and income in that department, like this:
` DEPTNO ENAME SAL COMM INCOME
10 CLARK 2450 2450
10 KING 5000 5000
10 MILLER 1300 1300
10 8750 8750
20 ADAMS 1100 1100
20 FORD 3000 3000
20 JONES 2975 2975
20 SCOTT 3000 3000
20 SMITH 800 800
20 10875 10875
30 ALLEN 1600 300 1900
30 BLAKE 2850 2850
30 JAMES 950 950
30 MARTIN 1250 1400 2650
30 TURNER 1500 0 1500
30 WARD 1250 500 1750
30 9400 2200 11600(This relies on the fact that ename is unique.) Getting those results is pretty easy, using GROUPING SETS:
SELECT deptno
, ename
, SUM (sal) AS sal
, SUM (comm) AS comm
, SUM ( sal
+ NVL (comm, 0)
) AS income
FROM scott.emp
GROUP BY GROUPING SETS ( (deptno)
, (deptno, ename)
ORDER BY deptno
, ename
;Notice that we're displaying SUM (sal) on each row. Most of the rows in the output are "groups" consisting of only one row from the table, so the SUM (sa) for that goup will be the sal for the one row in the group.
Edited by: Frank Kulash on Nov 23, 2011 2:03 PM
Added GROUPING SET example -
Need help with SQL for Pie Chart
I am trying to create a pie charge which would have 3 slices.
Following sql gives me the expected values when I run the sql command:
select
round(avg(CATEGORY_1 + CATEGORY_2 + CATEGORY_3 + CATEGORY_4 + CATEGORY_5),0) "OD Engagements",
round(avg(CATEGORY_6 + CATEGORY_7 + CATEGORY_13),0) "Talent Engagements",
round(avg(CATEGORY_8 + CATEGORY_9 + CATEGORY_10 + CATEGORY_11 + CATEGORY_12),0) "Other Engagements"
from OTD_PROJECT
where STATUS in ('Open','Hold')
I get 3 columns labeled: OD Engagements, Talent Engagements and Other Engagements with the correct averages based on the the data.
I have tried several ways to try to get this to work in the SQL for a pie chart, but keep getting the invalid sql message and it won't save. I also tried saving without validation, but no data is shown on the chart at all.
I want to have a pie, with 3 slices, one labeled OD Engagements with a value of 27, one labeled Talent Engagements with a value of 43 and one labeled Other Engagements with a value of 30. Then I want to be able to click on each pie slice to drill down to a secondary pie chart that shows the breakdown based on the categories included in that type.
Since I am not grouping based on an existing field I an unsure what the link and label values should be in the chart sql.You'll need something like the below. I have no idea what the URL for the drilldown needs to be. It should create an appropriate link in your app for the particular slice. Mainly the code below breaks the SQL results into three rows rather than three columns. It may well have a syntax error since I can't test.
select linkval AS LINK,
title AS LABEL,
calc_val AS VALUE
FROM (SELECT 'OD Engagements' AS title,
round(avg(CATEGORY_1 + CATEGORY_2 + CATEGORY_3 + CATEGORY_4 + CATEGORY_5),0) AS calc_val,
'f?p=???:???:' || v('APP_SESSION') || '::NO:?' AS LINKVAL
from OTD_PROJECT
where STATUS in ('Open','Hold')
UNION ALL
SELECT 'Talent Engagements' AS title,
round(avg(CATEGORY_6 + CATEGORY_7 + CATEGORY_13),0) AS calc_val,
'f?p=???:???:' || v('APP_SESSION') || '::NO:?' AS LINKVAL
from OTD_PROJECT
where STATUS in ('Open','Hold')
UNION ALL
SELECT 'Other Engagements' AS title,
round(avg(CATEGORY_8 + CATEGORY_9 + CATEGORY_10 + CATEGORY_11 + CATEGORY_12),0) AS calc_val,
'f?p=???:???:' || v('APP_SESSION') || '::NO:?' AS LINKVAL
from OTD_PROJECT
where STATUS in ('Open','Hold')
); -
Hi All,
I have a requirement to split the below query based on conditions. This should be done in SQL.
SELECT cv.chr_val_code MOD_CODE,
cv.chr_val_id MOD_ID,
f_char_value_dscr(cv.chr_val_id, 4,1) MOD_DSCR,
f_char_value_dscr(schsg.prnt_chr_val_id,4, 1) MOD_SCHEMA,
cv.mod_typ MOD_TYPE,
f_char_value_dscr(sgpg.prnt_chr_val_id,4,1) MOD_SUPERGROUP,
f_char_value_dscr(sgpg.chld_chr_val_id,4,1) MOD_PRODUCTGROUP,
f_char_value_dscr(lpgpc.CHLD_CHR_VAL_ID,4,1) "LOCAL PC",
f_char_value_dscr(lpgpc.PRNT_CHR_VAL_ID,4,1) "LOCAL PRODUCTGROUP",
f_char_value_dscr(lsgpg.CHLD_CHR_VAL_ID,4,1) "LOCAL SUPERGROUP",
cv.cnsldtd_item_mod MOD_CONSOLIDATED
FROM chr_val_t cv
INNER JOIN chr_t c
ON c.chr_id = cv.chr_id
AND c.chr_typ_ref_id = pkg_grd_global.f_get_ref_id_by_val('GLOBAL MODULE','CHARACTERISTIC TYPE')
OR c.chr_typ_ref_id = pkg_grd_global.f_get_ref_id_by_val('LOCAL PC','CHARACTERISTIC TYPE')
INNER JOIN hier_elmnt_t pgmod
ON cv.chr_val_id = pgmod.chld_chr_val_id
INNER JOIN hier_elmnt_t sgpg
ON sgpg.chld_chr_val_id = pgmod.prnt_chr_val_id
INNER JOIN hier_elmnt_t schsg
ON schsg.chld_chr_val_id = sgpg.prnt_chr_val_id
INNER JOIN hier_elmnt_t lpgpc
ON cv.chr_val_id = lpgpc.CHLD_CHR_VAL_ID
INNER JOIN hier_elmnt_t lsgpg
ON lsgpg.CHLD_CHR_VAL_ID = lpgpc.PRNT_CHR_VAL_ID
WHERE cv.del_ind = 'N' and c.rgn_id = 9 --GLOBAL REGION ID
Basically what i need to do now is, say suppose c.rgn_id = 9 then i need to show the below fields
cv.chr_val_id MOD_ID,
f_char_value_dscr(cv.chr_val_id, 4,1) MOD_DSCR,
f_char_value_dscr(schsg.prnt_chr_val_id,4, 1) MOD_SCHEMA,
cv.mod_typ MOD_TYPE,
f_char_value_dscr(sgpg.prnt_chr_val_id,4,1) MOD_SUPERGROUP,
f_char_value_dscr(sgpg.chld_chr_val_id,4,1) MOD_PRODUCTGROUP
and if c.rgn_id != 9 then i need to show
f_char_value_dscr(lpgpc.CHLD_CHR_VAL_ID,4,1) "LOCAL PC",
f_char_value_dscr(lpgpc.PRNT_CHR_VAL_ID,4,1) "LOCAL PRODUCTGROUP",
f_char_value_dscr(lsgpg.CHLD_CHR_VAL_ID,4,1) "LOCAL SUPERGROUP",
cv.cnsldtd_item_mod MOD_CONSOLIDATED
both the above 2 split conditins should be fetching from the same FROM clause
pls advise..Hi Harry (nice name by the way),
Do you actually want to have different numbers of columns in the output or do you just want null shown if rgn_id is/isnt 9?
If you just want nulls then you can do it easily with a case statement
i.e. case rgn_id=9 then xxx else xxx - you can google an example easy enough
If you want dynamic columns it gets more complicated and you may have to look at pipelined functions or some other solution to do this.
Cheers,
Harry -
Need help with Pixi Plus setup on Telstra Australia
If any one can help i would be very grateful.
I'm in Australia and wanted to try out a WebOS phone as a replacement for my Treo 680.
I did the research and found that AT&T GSM phones will work here in Australia.
I found a new unactivated Pixi Plus on eBay, as it was the same WebOS as Pre thought i would give it a try and bought it.
So my new Pixi Plus arrived three weeks ago, put my sim in and found it was locked to AT&T. I rang AT&T and was told it will be locked till end of December because of there system. The eBay seller said it was locked and may be able to be unlocked.
I found a way around this problem as i didn't want to wait that long.
I ordered a Rebelsim Card that arrived a few days ago, put it in and seems to work. Now have Telstra Mobile in the top corner.
Now my problem really starts.
I can't get onto the web to activate and set up my '' cloud ''
My phone is asking for APN:
I have tried:
telstra.iph
telstra.internet
Nothing works.
I can't get out of this screen without a APN:
This APN: thing i didn't find out untill i got the phone. Can't find much info at all on the subject.
Why is Palm making it so difficult, don't they want to sell phones.
Had no problems with my 650 and 680's bought form overseas.
Can anyone point me in the right direction please.
Thanks
Peter
Post relates to: Pre Plus p100una (AT&T)Called Sonos, they got me all setup.
-
Need help with SQL Query (query for certain IDs in a table and then IDs not in result set)
OK. This is hard to explain but that may be my problem in constructing the query.
I have a table that has a list of jobs. The jobs information in this table, among other things, is a short description of the job itself (think "title" in phrase form), date, and ID.
So I can query the table to get all the jobs for a particular grouping of IDs (the only ones I am interested in) that ran successfully for a given time period. But what I want are all the jobs that did not succeed (or therefore are not present in the table) for this group of jobs and for a certain date range. But these are not the only job id's in the table.
To get the successful ones I do the following:
SELECT id,short_desc FROM my_table where
id IN('1230', '1231', '1232', '1239', '1244', '1245',
'1246', '1247', '1248', '1272', '1280', '1281', '1282',
'1283', '1284', '1285', '1286', '1249', '1250', '1251',
'1252', '1253', '1255', '1233', '1234', '1235', '1236',
'1237', '1238', '1256', '1257','1258', '1254', '1290','1310')
AND the_date > = SYSDATE - 23/24
AND to_char(the_date, 'DD-MON-YYYY') = TO_CHAR(CURRENT_DATE, 'DD-MON-YYYY')
I have tried to use another AND clause with NOT IN and the group or NOT EXISTS but that doesn't work as there are other jobs captured in this table with id's of course. I am only concerned with these id's:
IN('1230', '1231', '1232', '1239', '1244', '1245',
'1246', '1247', '1248', '1272', '1280', '1281', '1282',
'1283', '1284', '1285', '1286', '1249', '1250', '1251',
'1252', '1253', '1255', '1233', '1234', '1235', '1236',
'1237', '1238', '1256', '1257','1258', '1254', '1290','1310')
Someone said to use a temp table. I don't think I have permission and I haven't tried as I want to do this in one query if possible.
After thinking about this I am at a loss. I tried to do this in the front end but it just became too messy.You do not need a physical temp table. You need an in-line view:
WITH list as (
SELECT '1230' id FROM DUAL UNION ALL
SELECT '1231' FROM DUAL UNION ALL
SELECT '1232' FROM DUAL UNION ALL
SELECT '1239' FROM DUAL UNION ALL
SELECT '1244' FROM DUAL UNION ALL
SELECT '1245' FROM DUAL UNION ALL
SELECT '1246' FROM DUAL UNION ALL
SELECT '1247' FROM DUAL UNION ALL
SELECT '1248' FROM DUAL UNION ALL
SELECT '1272' FROM DUAL UNION ALL
SELECT '1280' FROM DUAL UNION ALL
SELECT '1281' FROM DUAL UNION ALL
SELECT '1282' FROM DUAL UNION ALL
SELECT '1283' FROM DUAL UNION ALL
SELECT '1284' FROM DUAL UNION ALL
SELECT '1285' FROM DUAL UNION ALL
SELECT '1286' FROM DUAL UNION ALL
SELECT '1249' FROM DUAL UNION ALL
SELECT '1250' FROM DUAL UNION ALL
SELECT '1251' FROM DUAL UNION ALL
SELECT '1252' FROM DUAL UNION ALL
SELECT '1253' FROM DUAL UNION ALL
SELECT '1255' FROM DUAL UNION ALL
SELECT '1233' FROM DUAL UNION ALL
SELECT '1234' FROM DUAL UNION ALL
SELECT '1235' FROM DUAL UNION ALL
SELECT '1236' FROM DUAL UNION ALL
SELECT '1237' FROM DUAL UNION ALL
SELECT '1238' FROM DUAL UNION ALL
SELECT '1256' FROM DUAL UNION ALL
SELECT '1257' FROM DUAL UNION ALL
SELECT '1258' FROM DUAL UNION ALL
SELECT '1254' FROM DUAL UNION ALL
SELECT '1290' FROM DUAL UNION ALL
SELECT '1310' FROM DUAL
SELECT l.id,
nvl(short_desc,'This job failed') short_desc
FROM my_table m
WHERE RIGTH JOIN
list
ON (
m.id = l.id
AND
the_date > = SYSDATE - 23/24
AND
the_date < TRUNC(SYSDATE) + 1
SY. -
I need help with SQL Server 2012
Hi Everyone,
I am using the query pane to create a database with the data file and log file but keep getting this error message. I will be glad if someone can help.
You can see below the syntax:
Msg 5123, Level 16, State 1, Line 1
CREATE FILE encountered operating system error 5(Access is denied.) while attempting to open or create the physical file 'C:\project.mdf'.
Msg 1802, Level 16, State 4, Line 1
CREATE DATABASE failed. Some file names listed could not be created. Check related errors..
CREATE DATABASE project
ON
(Name= 'project_dat',
FILENAME ='C:\project.mdf',
SIZE = 10,
MAXSIZE = 100,
FILEGROWTH = 5)
LOG ON
(NAME = project_log,
FILENAME = 'C:\project.ldf',
SIZE =40,
MAXSIZE = 100,
FILEGROWTH = 10);Look at the second number in your constraints ValidBirthYear and ValidDeathYear. Do you mean to limit it to years between 1000-1199 and 2000-2199? Also, your ValidDeathYear constraint is using DateOfBirth.
CONSTRAINT
ValidBirthYear
CHECK
(DateOfBirth LIKE '[1-2]
[0-1] [0-9] [0-9]'),
CONSTRAINT
ValidDeathYear
CHECK
(DateOfBirth LIKE '[1-2]
[0-1] [0-9] [0-9]'));
I'm very much a beginner so that may not fix your issue but it sure looks like the cause of the second message to me. -
table structure
Column Data __Type
game_id______Integer
home_team___String
away_team___String
home_score___Integer
away_score___Integer
game_note____String
The XML document should be displayed as:
<lacrosse>
<title>College Lacrosse Results</title>
_<team>
____team_name
____<wins>number of wins</wins>
____<losses>number of losses</losses>
____<opponent>
_________opponent_name
_________<location>home or away</location>
_________<for>goals scored</for>
_________<against>goals given up</against>
____</opponent>
____<opponent>
____</opponent>
_</team>
_<team>
_</team>
</lacrosse>
I'm not really sure what my Statements to query the database should be.
My code so far is as such:
import java.sql.*;
import java.io.*;
import org.w3c.dom.*;
import org.apache.xerces.dom.*;
import org.apache.xml.serialize.*;
import javax.xml.*;
import org.apache.xml.serialize.OutputFormat;
public class DBtoXML {
public static final String DB_URL = "jdbc:mysql://localhost/test";
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String USERNAME = "'keith'@'localhost'";
public static final String PASSWORD = "keith";
public static final String OUTPUTFILE = "C:\\Test.xml";
public static final String SQL1 = "";
* @param args
public static void main(String[] args)
throws ClassNotFoundException
// make JDBC connection with Xerxes
try
Class.forName(DRIVER).newInstance();
Connection connection = DriverManager.getConnection(DB_URL);
// retrieve query result from database, store in ResultSet object
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(SQL1);
// build scores XML DOM
Document xmlDoc = buildScoresXML(resultSet);
// write to flat file
File outputFile = new File(OUTPUTFILE);
printDOM(xmlDoc, outputFile);
connection.close();
catch (InstantiationException ie)
ie.printStackTrace();
catch (SQLException sqle)
sqle.printStackTrace();
catch (IllegalAccessException iae)
System.out.println("Error generating connection: " + iae);
catch (Exception e)
System.out.println(e);
} //end main()
* buildScoresXML() - build Document from MySQL database
* @param resultSet
* @return - XML object to main() to be written to flat file
* @throws Exception
private static Document buildScoresXML(ResultSet rs)
throws Exception
Document xmlDoc = new DocumentImpl();
// create root element
Element rootElement = xmlDoc.createElement("lacrosse"); //has children
xmlDoc.appendChild(rootElement);
while(rs.next())
// create elements child elements of lacrosse (title, team)
Element title = xmlDoc.createElement("title");
rootElement.appendChild(title);
Element team = xmlDoc.createElement("team"); //has children
rootElement.appendChild(team);
// create child elements of team (wins, losses, opponent)
Element wins = xmlDoc.createElement("wins");
team.appendChild(wins);
Element losses = xmlDoc.createElement("losses");
team.appendChild(losses);
Element opponent = xmlDoc.createElement("opponent"); //has children
team.appendChild(opponent);
// create child elements of opponent (location, for, against)
Element location = xmlDoc.createElement("location");
opponent.appendChild(location);
Element goalsFor = xmlDoc.createElement("for");
opponent.appendChild(goalsFor);
Element against = xmlDoc.createElement("against");
opponent.appendChild(against);
return xmlDoc;
} //end buildScoresXML()
* printDOM() - write contents of XML document passed onto it to a file
* @param xmlDoc
* @param outputFile
* @throws Exception
private static void printDOM(Document xmlDoc, File outputFile)
throws Exception
OutputFormat outputFormat = new OutputFormat("XML", "UTF-8", true);
FileWriter fileWriter = new FileWriter(outputFile);
XMLSerializer xmlSerializer = new XMLSerializer(fileWriter, outputFormat);
xmlSerializer.asDOMSerializer();
xmlSerializer.serialize(xmlDoc.getDocumentElement());
} // end DBtoXML
Not sure where to go from here
Edited by: habituallinecrosser on Mar 23, 2009 2:10 PMI apologize for that scatter-brained, half-arsed post there =(
It's not becoming of me to clutter the board with that, nor to be so vague.
Anyway...
Briefly, the requirements for this assignment are:
To create the an XML document in the above format, using JDBC and DOM, from the data stored within the scores database, which contains the above listed fields.
I have been supplied with a CSS file and an XSD file, too.
My line of work is not software development, and I am not familiar with the XML APIs, nor JDBC.
I'm somewhat thinking out loud here, but my approach would be:
1. create a Team class with
String name
int wins
int losses
ArrayList games
the inner class Games will have:
String opponentName
Enum location (home, away)
int goalsScored
int goalsAllowed
2. create class TeamsLoader
-will extract each individual team from the scores table (using a "select distinct home_team from scores", followed by query to pick up any teams that were only in away_team column) and add them to an ArrayList<Team>
3. create class TeamRecordsCollector
-will produce ResultSet of "select* from scores" statement
-pass each index of ArrayList<Team> through each game_ID and compare team.Name with resultSet.home_team || resultSet.away_team for equality, and if equal, add the data to the Team
5. create a Document (rootElement = lacrosse) and iterating through the ArrayList<team> using a loop, adding the Elements during the loop
Is this making sense?
6. wrap FileWriter, OutputFormat in XMLSerializer to create flat file -
I am trying to build a query that sums up 12 columns depending on some accounting variables.
example:
SELECT gbmcu, gbco, gbfy,'',SUM(gban01 gban02 gban03 gban04 gban05+gban06+gban07+gban08+gban09+gban10+gban11+gban12) AS Oil_Volumes
FROM PRODDTA.F0902
WHERE GBCO = '00099'
AND GBFY = 5
AND GBLT = 'QU' AND GBOBJ = 5015 AND GBSUB = '105'
GROUP BY gbmcu, gbco, gbfy
The condition that changes is :AND GBLT = 'QU' AND GBOBJ = 5015 AND GBSUB = '105'
I need to do this for 17 different conditions - I need to make the query as optimized as possible.
I tried using a case statement but that takes forever (the table is over 4 million records to scan through).
Please let me know if anyone has any suggestions on how to create something to perform these calculations.
thanks,
PamI think I would tend to write that query as:
SELECT gbmcu, gbco, gbfy,
SUM(CASE WHEN gblt = 'QA' AND gbobj = 5015 AND gbsub = '105' THEN
gban01+gban02+gban03+gban04+gban05+gban06+gban07+gban08+gban09+gban10+gban11+gban12 END) Oil_Sales
SUM(CASE WHEN gblt = 'QU' AND gbobj = 5015 AND gbsub = '105' THEN
gban01+gban02+gban03+gban04+gban05+gban06+gban07+gban08+gban09+gban10+gban11+gban12 END) Oil_Volumes
FROM proddta.f0902
WHERE gbco = '00099' and
gbfy = 5 and
gblt IN ('QA', 'QU') and
gbpbj = 5015 and
gbsub = '105'
GROUP BY gbmcu, gbco, gbfySUM the CASE rather than CASE SUM. Also, as written, your query will look at all of the records in f0902 whether or not they meet one of the Case criteria, so I would put the required values in the WHERE clause as well. Your samples only show gblt changing, so you may need to make the gbpbj and gbsub predicates IN lists as well.
If the query runs in 1.5 hours calculating one value, I would expect it to be about the same calculating 17 values, since I would bet that most of the run time is accessing the table rather than doing the math. It would almost certainly be faster than running essentially the same query 17 times.
Indexes on some or all of the columns in the WHERE clause may help, depending on how selective the columns are. At a guess, I would suggest that gbco and gbfy would be good candidates.
Finally, are you sure that gbsub is a character field? The only example we have is a number.
HTH
John
Maybe you are looking for
-
I just switched to a MacBook from a different mac and I am trying to be careful of what I am importing (my old mac has all of my music and movies, etc). I don't want to clutter this new mac with duplicate songs etc. but I have a fairly extensive mus
-
Hi I would like to display Bex report or web report into Power point, I never seen this feature anywhere, is there anybody has idea about this or is there any other tools are supporting. Thx in advance. Regards Venkatuk
-
Weblogic server installation - multiple instances in different ports
Hi I want to install weblogic server(10.0) in my system but it should have three instances running on different ports(equivalent to 3 servers running on the same host). The application hosted on one server will be interacting with the applications ho
-
I have copies of the bookmarks, passwords, etc ready to put on the new computer with Windows 7 but they put things in different places than the other Windows. So where do these files go?
-
Is there the availability of a FTP download of the 4.7 Desktop Softare
The WEB download load is so slow...... to download the 200K plus file (470_b050_english.exe) , like over 6 hrs at 9k/sec. FTP is faster if available.