Need Some Calculation in Query
i have following sample data
select * from temp ;
CODE DDATE STAT CO_CODE COM FND_CODE FUND AMOUNT UNITS UBAL
76 24/06/2010 I 1 A B C 28 X Y Z 59854592 5787134.11 5787134.11
76 29/06/2010 R 1 A B C 28 X Y Z -1690984.6 4096149.47
07/07/2010 I 1 A B C 28 X Y Z 143454.173 4239603.65
76 19/07/2010 R 1 A B C 28 X Y Z -1393464.6 2846139.00
I need a query that will display all feilds with this calculation
continuee after UBAL
59854592(amount) / (Units) 5787134.11 = Avg (10.3427)
CODE DDATE STAT CO_CODE COM FND_CODE FUND AMOUNT UNITS UBAL Avg ABal
76 24/06/2010 I 1 A B C 28 X Y Z 59854592 5787134.11 5787134.11 10.3427 59854592
2nd line
If STAT = R then
-> Units * Above AVG = amount
-> Above ABal (59854592) - Current Line Amount (17489346) = ABal 42365246
-> Abal / Ubal = Avg
76 29/06/2010 R 1 A B C 28 X Y Z 17489346 -1690984.6 4096149.47 10.3427 42365246
(1690984.6*10.3427)
3rd Line
If STAT = I
-> Abal same as Above 42365246
-> Abal / Ubal = Avg
07/07/2010 I 1 A B C 28 X Y Z 143454.173 4239603.65 9.9927 42365246
4th line (same as 2nd line)
If STAT = R then
-> Units * Above AVG = amount
-> Above bal - Current Line Amount = ABal
-> Abal / Ubal = Avg
76 19/07/2010 R 1 A B C 28 X Y Z 13924473 -1393464.6 2846139.00 9.9927 28440773
Need your Help
Ahmed,
You may have to tweak the rounding a little, but this'll get you started:
SQL> create table mytable (code,ddate,stat,co_code,com,fnd_code,fund,amount,units,ubal)
2 as
3 select 76, date '2010-06-24', 'I', 1, 'A B C', 28, 'X Y Z', 59854592, 5787134.11, 5787134.11 from dual union all
4 select 76, date '2010-06-29', 'R', 1, 'A B C', 28, 'X Y Z', null, -1690984.6, 4096149.47 from dual union all
5 select null, date '2010-07-07', 'I', 1, 'A B C', 28, 'X Y Z', null, 143454.173, 4239603.65 from dual union all
6 select 76, date '2010-07-19', 'R', 1, 'A B C', 28, 'X Y Z', null, -1393464.6, 2846139.00 from dual
7 /
Table created.
SQL> select code
2 , ddate
3 , stat
4 , co_code
5 , com
6 , fnd_code
7 , fund
8 , amount
9 , units
10 , ubal
11 , myavg "Avg"
12 , abal "ABal"
13 from mytable
14 model
15 partition by (co_code,com,fnd_code,fund)
16 dimension by (row_number() over (partition by co_code,com,fnd_code,fund order by ddate)-1 rn)
17 measures (code,ddate,stat,amount,units,ubal,0 myavg,0 abal)
18 rules iterate (100) until (ddate[iteration_number+1] is null)
19 ( amount[iteration_number] = case stat[iteration_number]
20 when 'R' then round(abs(units[iteration_number]) * myavg[iteration_number-1])
21 else amount[iteration_number]
22 end
23 , abal[iteration_number] = case stat[iteration_number]
24 when 'I' then nvl(abal[iteration_number-1],amount[iteration_number])
25 when 'R' then abal[iteration_number-1] - amount[iteration_number]
26 end
27 , myavg[iteration_number] = round(abal[iteration_number] / ubal[iteration_number],4)
28 )
29 order by co_code
30 , com
31 , fnd_code
32 , fund
33 , ddate
34 /
CODE DDATE S CO_CODE COM FND_CODE FUND AMOUNT UNITS UBAL Avg ABal
76 24-06-2010 00:00:00 I 1 A B C 28 X Y Z 59854592 5787134.11 5787134.11 10.3427 59854592
76 29-06-2010 00:00:00 R 1 A B C 28 X Y Z 17489346 -1690984.6 4096149.47 10.3427 42365246
07-07-2010 00:00:00 I 1 A B C 28 X Y Z 143454.173 4239603.65 9.9927 42365246
76 19-07-2010 00:00:00 R 1 A B C 28 X Y Z 13924474 -1393464.6 2846139 9.9928 28440772
4 rows selected.Regards,
Rob.
Similar Messages
-
Need some Infor regarding Query Previliges
Hello Friends,
I am having a query which is doing a select from a collection of tables.
The query makes use of a procedure where I am passing some values.
But when I run it I get
ORA 01031-Insufficient Previliges Exception.
but when i comment the procedure part/line in the query.
It gets executed (here anyway it shows empty tables,but atleast it executes).
SO I thought if there is something in oracle,that, we can set previliges for the procedure which are different than the query itself(SELECT...). Considering the case above.
I hope you have got my problem.
I don't have any idea what needs to be done.
Thanks
VishalDoes the user trying to run the procedure have EXECUTE access on the procedure? You would grant this privilege with something like
GRANT EXECUTE ON <<procedure name>>
TO <<user name>>Justin
Distributed Database Consulting, Inc.
http://www.ddbcinc.com/askDDBC -
Access Web App - Need some advice with query (text to number problem)
In an Access Web App I want to create a query.
I have two tables which are related but in a bit complicated way. For some reason I have a text field in which I save a number. This number relates to the ID of another table. When I combine these two tables in a query, it's not working because the textfield
cannot query the (ID)number field.
Is there a way, in this query so that I covert the text field to a number so the query will work?
I tried to do it with the "Parse" function but no luck, so far.
Thanks, MikeHi Mike,
Based on the description, you want to create a query by joining a text filed with number filed?
Did I understood correctly? If so, as far as I test, it works in Access 2013 web app. Here is the screen shot for your reference:
If I misunderstood, please feel free to let me know.
Regards & Fei
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
Need some guidance - SQL Query Bind Variables for VO Object
Hi,
I'm trying to customize a custom page and I'm new to this. Can you please guide me or send me an example on how to do this?
1) VO is having the query as "SELECT INVOICE_NUM, INVOICE_DATE, INVOICE_AMOUNT, ...... from AP_INVOICES_ALL" (no parameters in the where clause)
2) Added VO to AM
3) XML PG is designed with MainRN, QueryRN, and Instance of VO1 as Table region. Selected INVOICE_NUM, INVOICE_DATE as Searchable. QueryRN is ResultbasesSearch.
4) Deployed to E-Biz and users were able to query using INVOICE_NUM or INVOICE_DATE fields that are available in the QueryRN.
Now, they want to add FROM_INVOICE_DATE and TO_INVOICE_DATE to the Search Condition. So, I have added the condition in the VO Query as "SELECT INVOICE_NUM, INVOICE_DATE, INVOICE_AMOUNT, ...... from AP_INVOICES_ALL WHERE INVOICE_DATE between :0 and :1".
How to add these fields FROM_INVOICE_DATE and TO_INVOICE_DATE to the QueryRN? These are not part of VO.
How to bind them to :0 and :1? I don't see any controller here? Do I need set a new controller and write logic for getting result set?
Any sample script or link would really help.
Thanks in advance.
RamHi Ram,
Hmmm, it is interesting.
Add two attributes to the page fromDate and toDate and in the controller class capture the values (like String fromDate = pageContext.getParameter("FromDate");) and invoke a method from AM and pass these parameters.
In the AM method call a method of VO and the VOImpl set and pass the bind parameters and execute the query again.
like
setWhereClause(" from_date = :1 AND to_date = :2");
setWhereClauseParams(null); // Always reset
setWhereClauseParam(0, fromDate);
setWhereClauseParam(1, toDate);
executeQuery();
Hope this will answer your question.
Krishna. -
Hey all, I have the following scenario,
Table A
Column1
2
3
5
Table B
Column2
7
5
4
Table C
Column1, Column2
2,7
3,8
5,10
So basically I need to compare in a way that the combination of the values in A AND B match the recordset in C as such,
select column1, column2 from Table A, Table B
where a combination of both those columns exists in Table C. Therefore in the above example, this query should return "2,7" as the output. Any ideas would be appreciated.This should do?
SQL> select c.col1, c.col2
2 from c
3 where (c.col1, c.col2) in (select col1, col2
4 from (select c.col1 col1
5 from C, a
6 where c.col1 = a.col1) q1
7 ,(select c.col2 col2
8 from C, b
9 where c.col2 = b.col1) q2
10 )
11 /
COL1 COL2
2 7Cheers
Sarma. -
HI Experts,
I need some calculations at query level,
find the below user requirement.
And one more thing we are not authorised to use Customer exits.
SELECT
[FA No] As [FA No],
[FA Description] As [FA Description],
Sum( CASE WHEN [Posting Date] < @fromDate THEN Amount ELSE 0 END) AS [Starting Balance],
Sum( CASE WHEN [Posting Date] >= @fromDate AND [Posting Date] <= @toDate THEN [Debet Amount] ELSE 0 END) AS [Debet Amount],
Sum( CASE WHEN [Posting Date] >= @fromDate AND [Posting Date] <= @toDate THEN [Credit Amount] ELSE 0 END) AS [Credit Amount],
Sum( CASE WHEN [Posting Date] <= @toDate THEN Amount ELSE 0 END) AS [Ending Balance],
Sum( CASE WHEN [Posting Date] >= @fromDate AND [Posting Date] <= @toDate THEN [Amount] ELSE 0 END) AS [Net Change]
FROM FA06data
GROUP BY [FA No], [FA Description]
Please help as early as you can.
Thanks,
NaveenThanks for your responce.
we are using Sql with the query designer.
what we can use? like calculated key figure. -
Need some help with the Select query.
Need some help with the Select query.
I had created a Z table with the following fields :
ZADS :
MANDT
VKORG
ABGRU.
I had written a select query as below :
select single vkorg abgru from ZADS into it_rej.
IT_REJ is a Work area:
DATA : BEGIN OF IT_REJ,
VKORG TYPE VBAK-VKORG,
ABGRU TYPE VBAP-ABGRU,
END OF IT_REJ.
This is causing performance issue. They are asking me to include the where condition for this select query.
What should be my select query here?
Please suggest....
Any suggestion will be apprecaiated!
Regards,
DeveloperHello Everybody!
Thank you for all your response!
I had changes this work area into Internal table and changed the select query. PLease let me know if this causes any performance issues?
I had created a Z table with the following fields :
ZADS :
MANDT
VKORG
ABGRU.
I had written a select query as below :
I had removed the select single and insted of using the Structure it_rej, I had changed it into Internal table
select vkorg abgru from ZADS into it_rej.
Earlier :
IT_REJ is a Work area:
DATA : BEGIN OF IT_REJ,
VKORG TYPE VBAK-VKORG,
ABGRU TYPE VBAP-ABGRU,
END OF IT_REJ.
Now :
DATA : BEGIN OF IT_REJ occurs 0,
VKORG TYPE VBAK-VKORG,
ABGRU TYPE VBAP-ABGRU,
END OF IT_REJ.
I guess this will fix the issue correct?
PLease suggest!
Regards,
Developer. -
Need Help by some % calculation
Hi Guys,
i need some help calculating something.
I have 5 boxes; "boxA" - "boxB" - "boxC" - "boxD" and "boxE". Box A–C are sums coming from other fields.
"boxD" represent the VTA – and can be just 19% ore 0%.
This means that "boxE" = ("boxA" + "boxB" + "boxC") * "boxD" ("box D" is equal with 0,19 – if the customer types 19% in the field – ore "0" (zero) – by leaving the "boxD" empty or typing the value "0" inside. A multiplication with 0 would be false, so it had to be ignored if the content of the "boxD" is 0)
I suppose it will be something with "if" and "else" but how i say, I'm a greenhorn in this domain.
Actually i found something that could help but i thing some parts – the definition of var v4, if v4 get the value 19% ore 0% – are missing.
(function() {
// Get the field values, as numbers
var v1 = +getField("boxA").value;
var v2 = +getField("boxB").value;
var v3 = +getField("boxC").value;
var v4 = +getField("boxD").value;
// I suppose here comes some "if" "else" stuff for the definitoon of var4
// Perform the calculation; the result is the content of the "boxE"
var result = v4 * (v1 + v2 + v3);
// Set the value of this field to the result
event.value = result;I would make sure you are not having a problem with using the "," as the decimal separator.
What problem are you having?
Is there an error in the JavaScript console?
If so, what is the exact wording?
Have you examined the values within the script to make sure you are getting the value you are expecting? -
In order to some calculator functions on the "Bankrate" website I need to enable the Java Browser function. I can I accomplished that task?
In recent versions of Lion, Java is automatically disabled (for security reasons) if it goes unused for a certain amount of time. You can re-enable it in the General pane of the Java Preferences app, found in /Applications/Utilities. (Check the box at the top of that pane.) If trying to open Java Preferences results in a message asking if you want to install Java, you don't actually have Java yet. Click the install button to install it.
Note that having Java turned on in your web browser is dangerous, due to recent proliferation of malware that uses Java to install itself. -
Need some help formulating a query
I need to formulate a query to list the branch number, branch name, revenue_target, and the revenue_generated for each branch that fails to meet its revenue_target where the revenue_generated by a branch is the sum of the total amount of all orders for salespersons working at that branch. The total amount of an order is given by the sum of the total amount for products and the total amount for installation.
Here are the tables that I am presented with:
Table: EMPLOYEE
PK: employeeID
FK: empBranch references BRANCH
FK: empSupervisor references EMPLOYEE
EMPLOYEEID EMPLNAME EMPFNAME EMPTITLE EMPSTARTDATE EMPBRANCH EMPSALARY EMPSUPERVISOR
e1 Adam Alan CEO 11-JAN-02 b1 600000 -
e2 Bryson Brad branch_manager 01-FEB-03 b2 400000 e1
e3 Clay Cedric branch_manager 21-JUN-01 b3 450000 e1
e4 Day Daisy branch_manager 17-AUG-03 b4 480000 e1
e5 Engle Eva salesperson 01-JAN-04 b2 120000 e2
e6 Falcon Fred salesperson 01-JAN-02 b2 80000 e2
e7 Gandhi Gagan salesperson 01-JAN-03 b3 90000 e3
e8 Hee Hwang salesperson 01-JUN-04 b3 95000 e3
e9 Ingram Irene salesperson 24-SEP-02 b4 110000 e4
e10 Jerome John salesperson 25-AUG-02 b4 75000 e4
Table: BRANCH
PK: branchNumber
FK: branchManager references EMPLOYEE
BRANCHNUMBER BRANCHNAME BRANCHSTREET BRANCHCITY BRANCHSTATE BRANCHZIP REVENUETARGET BRANCHMANAGER
b1 branch1 9700 NW 41 St Miami FL 33178 800000 e1
b2 branch2 8700 SW 24 St Miami FL 33170 600000 e2
b3 branch3 E 200 47 St New York NY 11010 1000000 e3
b4 branch4 300 Park Avenue New York NY 10010 1200000 e4
Table: PRODUCT
PK: productCode
PRODUCTCODE PRODDESCRIPTION PRICE STOCKLEVEL
p1 carpet 40 10000
p2 tile 20 100000
p3 pergo 50 50000
Table: INSTALLATION
PK: installationType
INSTALLTYPE INSTALLDESCRIPTION RATE
i1 carpet installation 40
i2 tile installation 50
i3 pergo installation 60
Table: ORDERS
PK: orderNumber
FK: customerID references CUSTOMER
FK: salesPerson references EMPLOYEE
ORDERNUMBER ORDDATE SALESPERSON CUSTOMERID
o1 12-AUG-07 e5 c1
o2 14-DEC-07 e5 c2
o3 04-NOV-07 e5 c3
o4 15-AUG-07 e5 c4
o5 22-NOV-07 e10 c5
o6 01-JUL-07 e10 c6
o7 12-DEC-07 e6 c6
o8 30-NOV-07 e9 c2
Table: PRODLINE
PK: orderNumber + prodCode
FK: orderNumber references ORDERS
FK: prodCode references PRODUCT
ORDERNUMBER PRODCODE QUANTITY
o1 p1 1000
o1 p2 500
o2 p3 200
o3 p1 600
o3 p3 100
o4 p2 1000
o5 p2 800
Table: INSTLINE
PK: orderNumber + instType
FK: orderNumber references ORDERS
FK: instType references INSTALLATION
ORDERNUMBER INSTTYPE HOURS
o1 i1 20
o1 i2 30
o1 i3 10
o2 i1 10
o2 i2 20
o6 i1 20
o6 i2 10
o7 i3 10
o8 i2 20
I can write the queries to get the TOTAL_AMOUNT_FOR_ORDERS, TOTAL_AMOUNT_FOR_INSTALLATIONS, and BRANCHNUMBER, BRANCHNAME, REVENUETARGET. But I can't seem to put them all together.
Query 1:
SELECT *
FROM
(SELECT o.ORDERNUMBER, SUM(QUANTITY*PRICE) as TOTAL_AMOUNT_FOR_ORDERS
FROM ORDERS o, PRODUCT p, PRODLINE pl
WHERE o.ORDERNUMBER=pl.ORDERNUMBER
AND p.PRODUCTCODE=pl.PRODCODE
GROUP BY o.ORDERNUMBER
ORDER BY o.ORDERNUMBER) TOTORD
FULL JOIN
(SELECT o.ORDERNUMBER, SUM(HOURS*RATE) as TOTAL_AMOUNT_FOR_INSTALLATIONS
FROM ORDERS o, INSTALLATION i, INSTLINE il
WHERE o.ORDERNUMBER=il.ORDERNUMBER
AND i.INSTALLTYPE=il.INSTTYPE
GROUP BY o.ORDERNUMBER
ORDER BY o.ORDERNUMBER) TOTINS
ON
TOTORD.ORDERNUMBER=TOTINS.ORDERNUMBER
Query 2:
SELECT BRANCHNUMBER, BRANCHNAME, REVENUETARGET
FROM ORDERS o, EMPLOYEE e, BRANCH b
WHERE e.EMPLOYEEID=o.SALESPERSON
AND b.BRANCHNUMBER=e.EMPBRANCH
Can someone please assist?Hi,
895231 wrote:
I need to formulate a query to list the branch number, branch name, revenue_target, and the revenue_generated for each branch that fails to meet its revenue_target where the revenue_generated by a branch is the sum of the total amount of all orders for salespersons working at that branch. The total amount of an order is given by the sum of the total amount for products and the total amount for installation.
Here are the tables that I am presented with: ...Whenever you have a problem, please post CREATE TABLE and INSERT statements for your sample data, and the final results you want to get from that data.
Explain how you get those results from that data, with specific examples, such as "Branch b1 is included in the results because its revenue_target (which I can get from this query ...) is x, but the order total (which I can see from this query ...) is y, which is less than x. Branch b2 is not included because ..."
Always say which version of Oracle you're using
... I can write the queries to get the TOTAL_AMOUNT_FOR_ORDERS, TOTAL_AMOUNT_FOR_INSTALLATIONS, and BRANCHNUMBER, BRANCHNAME, REVENUETARGET. But I can't seem to put them all together.Thanks for posting these, but without CREATE TABLE and INSERT statements for your sample data, nobody can run them.
I don't think you need a FUL OUTER JOIN. If all you need is a grand total, UNION ALL would be more efficient. -
I have a huge report that gathers data about all facets of the company to display in one place. I have built a procedure to calculate and store the data (as it gets processed once and viewed often), but the query to display it is huge - about 1950 lines or 104 KB. I can run the report fine in SQL developer, but I need it in APEX, which is limited in its report area to 32KB per query. The report is basically the same chunk over and over referencing each of the saved calculations in a particular order. Here's a sample of a report section:
union
select 833 as SCTN_ID, 'Efficiency' as SCTN
, 'Variance' as TTL
, (select to_char(GOAL-ACTUAL) from vf_run_byweek_dtl a
where a.run_id = p.run_id and a.section = 'HARD_BRAKES'
and a.period_start = to_date(:P2007_LAST_DAY,'MM/DD/YYYY')-6) as WK1
, (select to_char(GOAL-ACTUAL) from vf_run_byweek_dtl a
where a.run_id = p.run_id and a.section = 'HARD_BRAKES'
and a.period_start = to_date(:P2007_LAST_DAY,'MM/DD/YYYY')-13) as WK2
, (select to_char(GOAL-ACTUAL) from vf_run_byweek_dtl a
where a.run_id = p.run_id and a.section = 'HARD_BRAKES'
and a.period_start = to_date(:P2007_LAST_DAY,'MM/DD/YYYY')-20) as WK3
, (select to_char(GOAL-ACTUAL) from vf_run_byweek_dtl a
where a.run_id = p.run_id and a.section = 'HARD_BRAKES'
and a.period_start = to_date(:P2007_LAST_DAY,'MM/DD/YYYY')-27) as WK4
, (select to_char(GOAL-ACTUAL) from vf_run_byweek_dtl a
where a.run_id = p.run_id and a.section = 'HARD_BRAKES'
and a.period_start = to_date(:P2007_LAST_DAY,'MM/DD/YYYY')-34) as WK5
, 'var' as CLASS
from vf_run_byweek p
where p.org_id = :P2007_ORG_ID
and p.last_day = to_date(:P2007_LAST_DAY,'MM/DD/YYYY')
...There are about 20 report areas - not all the same format - and each area usually has the target, actual, variance, and variance as % displayed for 5 weeks at a time on a rolling basis - so a 5x9 grid for each area once you add in variable column headers, etc. The sample above gives me one line of the 5 or so in a section.
I need some way to get around the 32K limit. I've tried building this as a view, but I need to pass in the parameters to select the correct date and organization. Can someone suggest a solution? (PS, I am trying to stay away from a stored procedure if possible as a standard report format will download to csv.)Okay, so this is my first foray into parameterized views, so if someone could help me understand. I created a page process to fire AFTER HEADER, BEFORE REGIONS containing the following:
-- Set the context for Min and max dates.
DBMS_SESSION.set_context (namespace => 'VF_PARAMS',
ATTRIBUTE => 'org',
VALUE => :P2007_ORG_ID
DBMS_SESSION.set_context(namespace => 'VF_PARAMS',
ATTRIBUTE => 'last_day',
VALUE => :P2007_LAST_DAY
);I created a sample view to get this working as such:
CREATE OR REPLACE VIEW V_VF (SECTION_NUM, SECTION, TITLE, WK1, WK2, WK3, WK4, WK5, CLASS)
as (
--100 Safety
select 110 as SCTN_ID, 'Safety' as SCTN
, '# of Safety Audits' as TTL
, 'Week of '||to_char(to_date(SYS_CONTEXT('VF_PARAMS', 'last_day'),'MM/DD/YYYY')-06,'Mon dd') as WK1
, 'Week of '||to_char(to_date(SYS_CONTEXT('VF_PARAMS', 'last_day'),'MM/DD/YYYY')-13,'Mon dd') as WK2
, 'Week of '||to_char(to_date(SYS_CONTEXT('VF_PARAMS', 'last_day'),'MM/DD/YYYY')-20,'Mon dd') as WK3
, 'Week of '||to_char(to_date(SYS_CONTEXT('VF_PARAMS', 'last_day'),'MM/DD/YYYY')-27,'Mon dd') as WK4
, 'Week of '||to_char(to_date(SYS_CONTEXT('VF_PARAMS', 'last_day'),'MM/DD/YYYY')-34,'Mon dd') as WK5
, 'colhdr' as CLASS
from dual
union
select 111 as SCTN_ID, 'Safety' as SCTN
, 'Goal' as TTL
, (select to_char(GOAL) from vf_run_byweek_dtl a
where a.run_id = p.run_id and a.section = 'AUDITS'
and a.period_start = to_date(SYS_CONTEXT('VF_PARAMS', 'last_day'),'MM/DD/YYYY')-6) as WK1
, (select to_char(GOAL) from vf_run_byweek_dtl a
where a.run_id = p.run_id and a.section = 'AUDITS'
and a.period_start = to_date(SYS_CONTEXT('VF_PARAMS', 'last_day'),'MM/DD/YYYY')-13) as WK2
, (select to_char(GOAL) from vf_run_byweek_dtl a
where a.run_id = p.run_id and a.section = 'AUDITS'
and a.period_start = to_date(SYS_CONTEXT('VF_PARAMS', 'last_day'),'MM/DD/YYYY')-20) as WK3
, (select to_char(GOAL) from vf_run_byweek_dtl a
where a.run_id = p.run_id and a.section = 'AUDITS'
and a.period_start = to_date(SYS_CONTEXT('VF_PARAMS', 'last_day'),'MM/DD/YYYY')-27) as WK4
, (select to_char(GOAL) from vf_run_byweek_dtl a
where a.run_id = p.run_id and a.section = 'AUDITS'
and a.period_start = to_date(SYS_CONTEXT('VF_PARAMS', 'last_day'),'MM/DD/YYYY')-34) as WK5
, 'gl' as CLASS
from vf_run_byweek p
where p.org_id = SYS_CONTEXT('VF_PARAMS', 'org')
and p.last_day = to_date(SYS_CONTEXT('VF_PARAMS', 'last_day'),'MM/DD/YYYY')
)But when I try to run the page, I get this error:
Error ORA-01031: insufficient privileges
Technical Info (only visible for developers)
is_internal_error: false
ora_sqlcode: -1031
ora_sqlerrm: ORA-01031: insufficient privileges
component.type: APEX_APPLICATION_PAGE_PROCESS
component.id: 376623425929869335
component.name: Set SYS_CONTEXT parameters for view
error_backtrace:
ORA-06512: at "SYS.WWV_DBMS_SQL", line 904
ORA-06512: at "APEX_040100.WWV_FLOW_DYNAMIC_EXEC", line 618
ORA-06512: at "APEX_040100.WWV_FLOW_PROCESS", line 128I tried granting CREATE ANY CONTEXT to several users including APEX_PUBLIC_USER and APEX_040100, but this didn't seem to work. I've read through several blog posts and documents, but I must be doing something wrong in my implementation of trying to set the SYS_CONTEXT values. I would greatly appreciate some enlightenment, as the documentation I have read kind of skips over the set of the context in the first place and goes right into use. I fear this is the piece I am missing, or I have read over it and it just isn't clicking. There is some mention of having to reference SYS_CONTEXT via a package, but this went straight over my head. -
Need suggestions with massive query
I have a huge report that gathers data about all facets of the company to display in one place. I have built a procedure to calculate and store the data (as it gets processed once and viewed often), but the query to display it is huge - about 1950 lines or 104 KB. I can run the report fine in SQL developer, but I need it in APEX, which is limited in its report area to 32KB per query. The report is basically the same chunk over and over referencing each of the saved calculations in a particular order. Here's a sample of a report section:
union
select 833 as SCTN_ID, 'Efficiency' as SCTN
, 'Variance' as TTL
, (select to_char(GOAL-ACTUAL) from vf_run_byweek_dtl a
where a.run_id = p.run_id and a.section = 'HARD_BRAKES'
and a.period_start = to_date(:P2007_LAST_DAY,'MM/DD/YYYY')-6) as WK1
, (select to_char(GOAL-ACTUAL) from vf_run_byweek_dtl a
where a.run_id = p.run_id and a.section = 'HARD_BRAKES'
and a.period_start = to_date(:P2007_LAST_DAY,'MM/DD/YYYY')-13) as WK2
, (select to_char(GOAL-ACTUAL) from vf_run_byweek_dtl a
where a.run_id = p.run_id and a.section = 'HARD_BRAKES'
and a.period_start = to_date(:P2007_LAST_DAY,'MM/DD/YYYY')-20) as WK3
, (select to_char(GOAL-ACTUAL) from vf_run_byweek_dtl a
where a.run_id = p.run_id and a.section = 'HARD_BRAKES'
and a.period_start = to_date(:P2007_LAST_DAY,'MM/DD/YYYY')-27) as WK4
, (select to_char(GOAL-ACTUAL) from vf_run_byweek_dtl a
where a.run_id = p.run_id and a.section = 'HARD_BRAKES'
and a.period_start = to_date(:P2007_LAST_DAY,'MM/DD/YYYY')-34) as WK5
, 'var' as CLASS
from vf_run_byweek p
where p.org_id = :P2007_ORG_ID
and p.last_day = to_date(:P2007_LAST_DAY,'MM/DD/YYYY')
...There are about 20 report areas - not all the same format - and each area usually has the target, actual, variance, and variance as % displayed for 5 weeks at a time on a rolling basis - so a 5x9 grid for each area once you add in variable column headers, etc. The sample above gives me one line of the 5 or so in a section.
I need some way to get around the 32K limit. I've tried building this as a view, but I need to pass in the parameters to select the correct date and organization. Can someone suggest a solution? (PS, I am trying to stay away from a stored procedure if possible as a standard report format will download to csv.)Duplicate - Need help with massive query
-
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 -
Complex SQL calculated/Group Query
I am trying to write a complex aggregate query(s) to compile a standings table for a soccer league.
There are four related tables:
Matches
Goals
Players
teams
I have yet to finalize the database structure so I can add fields if necessary.
In the goals table I track the match that the goal was scored in and which player
scored it.
I am trying to create a query that will give me a standings table.
The fields I need to calculate are:
team name
Wins
Loses
Draws
For instance: There was a match on 4/21/2012. The players on HomeTeam(A) scored a combined 6 goals. The players on AwayTeam(B) scored 1 goal (All stored in the Goals table). Therefore, Hometeam won by a score of 6-1. I need
a query that spits out:
Team Wins Losses Draws
Points
HomeTeam(A) 1 0 0
3
AwayTeam(B) 0 1 0 3
Wins are worth 3 Losses 0 and Draws 1 point each team.
I am a long time SQL admin, but I think the complexity of calculating this is a little beyong me. I need some help to get where I need to be.Okay, I haven't yet been able to figure out the draws because of the trouble of linking back to both teams, but here's what I have so far.
First, here is the test data:
Declare @tvMatches Table (
MatchID int IDENTITY(1,1)
,MatchDate datetime
,HomeTeamID int
,AwayTeamID int
Declare @tvGoals Table (
GoalID int IDENTITY(1,1)
,MatchID int
,PlayerID int
,TeamID int
Declare @tvPlayers Table (
PlayerID int IDENTITY(1,1)
,TeamID int
,PlayerName varchar(30)
Declare @tvTeams Table (
TeamID int IDENTITY(1,1)
,TeamName varchar(20)
Insert @tvTeams
Select 'Winners'
Union All
Select 'Losers'
Union All
Select 'Friars'
Union All
Select 'Planes'
Insert @tvPlayers
Select 1, 'Bill'
Union All
Select 1, 'Jim'
Union All
Select 1, 'Ken'
Union All
Select 2, 'James'
Union All
Select 2, 'Smithy'
Union All
Select 2, 'Flip'
Union All
Select 3, 'Dave'
Union All
Select 3, 'Alan'
Union All
Select 3, 'Ethan'
Union All
Select 4, 'Naomi'
Union All
Select 4, 'Erland'
Union All
Select 4, 'Alejandro'
Insert @tvMatches
Select '20120101', 1, 2
Union All
Select '20120201', 3, 4
Union All
Select '20120301', 4, 1
--Winners beat Losers 3-2
--Planes beat Friars 4-2
--Winners beat Planes 2-1
Insert @tvGoals --Match, Player, Team
Select 1, 1, 1
Union All
Select 1, 3, 1
Union All
Select 1, 5, 2
Union All
Select 1, 6, 2
Union All
Select 1, 2, 1
Union All
Select 2, 7, 3
Union All
Select 2, 8, 3
Union All
Select 2, 10, 4
Union All
Select 2, 11, 4
Union All
Select 2, 12, 4
Union All
Select 2, 11, 4
Union All
Select 3, 1, 1
Union All
Select 3, 3, 1
Union All
Select 3, 11, 4
Using this test data, you want to compile the actual match outcomes. This can be problematic to do on the fly every time though, if you have a lot of matches or teams to calculate for. But, with a simple cte, we have:
;with cteMatches as
Select m.MatchID
,m.MatchDate
,m.HomeTeamID
,ht.TeamName HomeTeamName
,m.AwayTeamID
,at.TeamName AwayTeamName
,( Select Count(1)
From @tvGoals g
Where g.MatchID = m.MatchID
And g.TeamID = m.HomeTeamID
) HomeScore
,( Select Count(1)
From @tvGoals g
Where g.MatchID = m.MatchID
And g.TeamID = m.AwayTeamID
) AwayScore
From @tvMatches m
join @tvTeams ht
on m.HomeTeamID = ht.TeamID
join @tvTeams at
on m.AwayTeamID = at.TeamID
) --select * from cteMatches
This returns the MatchID, MatchDate, team information and the score. Basically, you have the match, team and player data tied to the goals table, so you just do a count (using correlated subqueries) to get the score of each team. Next step is
to calculate the winner and loser (and eventually whether there even was a winner) by comparing the scores:
,cteWinners as
Select cm.MatchID
,cm.HomeTeamID
,cm.HomeTeamName
,cm.AwayTeamID
,cm.AwayTeamName
,Case
When cm.HomeScore > cm.AwayScore Then cm.HomeTeamID
When cm.HomeScore < cm.AwayScore Then cm.AwayTeamID
Else 0
End WinningTeamID
,Case
When cm.HomeScore > cm.AwayScore Then cm.AwayTeamID
When cm.HomeScore < cm.AwayScore Then cm.HomeTeamID
Else 0
End LosingTeamID
From cteMatches cm
) --select * from ctewinners
This returns MatchID, team information and the ID's for winning and losing teams. For now it returns 0 if it's a draw. Once we know the outcomes of all the matches, we calculate the actual win/loss for each team:
,cteRecords as
Select t.TeamName
,Count( Case
When cw.WinningTeamID = t.TeamID Then 1
End
) Wins
,Count( Case
When cw.LosingTeamID = t.TeamID Then 1
End
) Losses
From @tvTeams t
join cteWinners cw
on t.TeamID = cw.HomeTeamID
or t.TeamID = cw.AwayTeamID
Group By t.TeamName
) --select * from cteRecords
That last cte returns just team name, and then the number of wins and losses for each team. This is where I got stuck with the draws, because I'm not quite sure yet how to properly assign a draw to both teams involved.
Now, finally you put it all together with some simple match to determine the points, and there you are:
Select TeamName
,Wins
,Losses
,(Wins * 3) Points
From cteRecords -
Laura, I need some code samples you mentioned...
Laura,
I posted a message a few days ago regarding calling Stored Procedures in my JDev 3.1 (JDK 1.2.2) BC4J application. I need to be able to call them two different ways. The first involves passing some parameters to the SP and recieving back the ResultSet. In the other instance I simply need to make a call to them to perform some tasks on the DB side. Nothing will be returned from these SP's. You discussed implementing the SQL as a VO and gave me some code showing me how I might do this. You also mentioned that it is possible to create a method on the AppMod and call this from the JSP client. I need to know which method should work best for me and to get the code samples for the second option.
Thanks.
RobHi,
Here is the code I used for the custom method on my VO (same could be used from the app module rather than a specific VO). The stored procedure I am calling here performs some calculations and returns an integer value:
public int getTotalHits(String mon, String year) {
CallableStatement stmt = null;
int total;
String totalhits = "{? = call walkthru.total_hits(?,?)}";
stmt = getDBTransaction().createCallableStatement(totalhits, 1);
try
// Bind the Statement Parameters and Execute this Statement
stmt.registerOutParameter(1,Types.INTEGER);
stmt.setString(2,mon);
stmt.setString(3,year);
stmt.execute();
total = stmt.getInt(1);
catch (Exception ex)
throw new oracle.jbo.JboException(ex);
finally
try
stmt.close();
catch (Exception nex)
return total;
After adding the custom method to your appmoduleImpl.java file and rebuilt your BC4J project, do the following:
1. Select the Application Module object and choose Edit from the context menu.
2. Click on the Client Methods page. You should see the method you added in the Available list.
3. Select the method and shuttle it to the Selected list.
4. Click Finish. You should see a new file generated under the application module object node in the Navigator named appmodule.java that contains the client stubs for your method.
5. Save and rebuild your BC4J project.
I wrote a custom web bean to use from my JSP page to call the method on my VO:
public class GetTotals extends oracle.jdeveloper.html.DataWebBeanImpl {
public void render() {
int totalhits;
try
Row[] rows;
// Retrieve all records by default, the qView variable is defined in the base class
qView.setRangeSize(-1);
qView.first();
rows = qView.getAllRowsInRange();
// instantiate a view object for our exported method
// and call the stored procedure to get the total
ViewObject vo = qView.getViewObject();
wtQueryView theView = (wtQueryView) vo;
totalhits = theView.getTotalHits(session.getValue("m").toString(),session.getValue("y").toString());
out.println(totalhits);
} catch(Exception ex)
throw new RuntimeException(ex.getMessage());
I just call the render method on this custom web bean from the JSP. I am not passing parameters to the render method of the bean, but instead access the parameters I need from the session:
session.getValue("m").toString()
I set these session parameters from the JSP that is called when the user submits their query criteria form. For example:
// get the view parameter from the form String month = request.getParameter("month");
String year = request.getParameter("year");
// store the information for reference later session.putValue("m", month); session.putValue("y", year);
Hope this helps.
Maybe you are looking for
-
I'vd just bought a new mainboard and CPU, which are: - mainboard MSI P35 Neo - Intel Core Quad Q6600 and started building up a new system with my old components: - ATI HD 3870 graphic - 2 GB RAM DDR2 533 - 250GB Hardisk Everything was in its place, b
-
Itunes for XP 64 bit machines ?????
I have an XP 64 bit machine. I just bought an Ipod touch. I want to get Itunes of course but it seesm they onyl support 32 bit machines and 64 bit machines on Vista. I have tried both of these but they will not load. How can I get itunes for 64 bit X
-
Quality certificate receipt without inspection lot
Hi Expert, I have activated QM control key with certificate type but no quality inspection type activated but will take material in quality inspection through IM. In this case where i can confirm certificate receipt. Regards, sandy
-
XI transport issue in repository.
XI 7.0 SP10 Hi, I imported a repository object. First time,i imported this object to target system successfully. Second time,i deleted a data type in source system,then import the new version to update target system.It seems no error occured accordin
-
Hi. I'd appreciate any help people can offer regarding this problem. I am creating some animations using Flash 8. Some work just fine. Others give me the following message when I try to add a new movie clip: One or more library items exists in docume