Order By in the Sub query
We cannot use ORDER BY in the Sub query.select * from emp where emp_no in (select emp_id from dept order by dept_no )
Get the below errorORA-00907: missing right parenthesis
Hello
user13024762 wrote:
To get the number of EMP table for maximum number of dept dept
If this is what you want, then do something like this:
select *
from emp
where emp_no in (
select MAX (emp_no) KEEP (DENSE_RANK LAST ORDER BY dept_no NULLS FIRST)
from dept
)
;
or maybe
select *
from emp
where emp_no = (
select emp_no
from dept
where dept_no = (
SELECT MAX (dept_no)
FROM dept
)
)
;
Depending on what you want in the case of a tie.
select * from emp where emp_no in (select emp_no from dept where rownum =1 order by dept_no desc)
The subquery that you posted above does not necessarily return the line containing the largest dept_no, since ROWNUM is affected before ORDER BY is done.
I hope that answers your question.
If not, post a small example of data (CREATE TABLE and only relevant columns, INSERT statements) for all tables and also post the results desired from these data.
Explain how you get these results from these data.
Tags: Database
Similar Questions
-
UPDATE on the same table in the sub query
DB version: 11.2
We have a table called SHP_GC_TRACK, which has about 8 million records with partitions. In the below UPDATE, it updates a column based on the SELECT on the same table in a subquery.
This UPDATE takes a long time to run and sometimes get hung up.UPDATE shp_gc_track a SET f_tran_proc = 'Y' WHERE last_update_date < (SELECT MAX (last_update_date) FROM shp_gc_track b WHERE a.shp_trx_rowid = b.shp_trx_rowid AND a.c_shp_inst = b.c_shp_inst AND a.f_tran_proc = b.f_tran_proc AND b.f_ltr_received = 'D' AND f_rec_code IN ('G', 'W') AND b.f_rec_status = 'B' AND b.c_shp_inst = :b1 ) AND a.c_shp_inst = :b1 AND a.f_ltr_received = 'D' -----------------> part of composite index AND a.f_tran_proc = 'N' -----------------> part of composite index AND a.f_rec_code IN ('G', 'W') --------------> part of composite index AND a.f_rec_status = 'B'; -----------------> part of composite index
We have a composite index on four columns f_ltr_received, f_rec_code, f_rec_status and f_tran_proc. Explain the plan shows that this composite index is used.
Any way to rewrite this query or suggestion?Steve_74 wrote:
DB version: 11.2We have a table called SHP_GC_TRACK, which has about 8 million records with partitions. In the below UPDATE, it updates a column based on the SELECT on the same table in a subquery.
UPDATE shp_gc_track a SET f_tran_proc = 'Y' WHERE last_update_date < (SELECT MAX (last_update_date) FROM shp_gc_track b WHERE a.shp_trx_rowid = b.shp_trx_rowid AND a.c_shp_inst = b.c_shp_inst AND a.f_tran_proc = b.f_tran_proc AND b.f_ltr_received = 'D' AND f_rec_code IN ('G', 'W') AND b.f_rec_status = 'B' AND b.c_shp_inst = :b1 ) AND a.c_shp_inst = :b1 AND a.f_ltr_received = 'D' -----------------> part of composite index AND a.f_tran_proc = 'N' -----------------> part of composite index AND a.f_rec_code IN ('G', 'W') --------------> part of composite index AND a.f_rec_status = 'B'; -----------------> part of composite index
This UPDATE takes a long time to run and sometimes get hung up.
We have a composite index on four columns f_ltr_received, f_rec_code, f_rec_status and f_tran_proc. Explain the plan shows that this composite index is used.
Any way to rewrite this query or suggestion?
Setting updates with subqueries may be difficult: (.) Unfortunately my suggestions below are of the try-it-and-see-what-happens variety - nothing of certain
First of all, check the index. Is it bitmap or tree? If the tree to see if the more restrictive columns are listed first - this can help with effectiveness of b-tree indexes. Also if the tree a composite bitmap for columns with lots of repeat values instead could help
Its a correlated subquery so that you cannot run just the subquery first put the result in a scalar varaiable and using the variable in the SQL instead. You can try putting the keys w/join subuqery results in a TWG first to use TWG in SQL to see if I/O is reduced together during these two operations.
You have the license for the parallel query option? Using parallel DML (this must be activated manually) can help. Check the documentation of the ALTER SESSION command to do so. In addition, the PARALLEL_INDEX() indicator could help
Display the SQL execution plan
-
Need to rotate the sub query using 11 g
Hello
Please find the below query
SELECT AGING_BUCKET_ID, DAYS_START, DAYS_TO, AR_AGING_BUCKET_LINES TYPE
WHERE AGING_BUCKET_ID = 3
It displays the data as below
AGING_BUCKET_ID DAYS_START DAYS_TO TYPE
3-9999 0 CURRENT
3 1 30 LAST
3 31 60 LAST
3 61 90 LAST
3 91 9999999 PAST
I tried to rotate the data, tried to make use of the PIVOT of the 11 g used the following query function
WITH AGBUCK AS
(
SELECT AGING_BUCKET_ID, DAYS_START, DAYS_TO, AR_AGING_BUCKET_LINES TYPE
WHERE AGING_BUCKET_ID = 3
) SELECT * FROM AGBUCK
PIVOT)
DAYS_START s1, s2 DAYS_TO, type
FOR AGING_BUCKET_ID
(3)
);
finished in the msg below:-ora-56902: wait for the aggregate within the operation of pivot function
can you please help me to fix it.
Concerning
YramHi, Yram,
Whenever you have a problem, after a few sample data and outcomes from these data.
Sorry, I can't make a good guess at what you want, and I'm not an Oracle 11 database now to test. I think you want something like this:WITH AGBUCK AS ( SELECT AGING_BUCKET_ID , DAYS_START , DAYS_TO || TYPE AS label FROM AR_AGING_BUCKET_LINES WHERE AGING_BUCKET_ID = 3 ) SELECT * FROM agbuck PIVOT ( MIN (days_start) FOR label IN ( '0 CURRENT' AS current_0 , '30 PAST' AS past_30 , '60 PAST' AS past_60 , '90 PAST' AS past_90 , '9999999 PAST' AS past_9999999 ) ) ;
The first thing inside the parentheses after the PIVOT keyword must be an aggregate function. If there is a one-to-one correspondence between the lines in the "input" table and cells in the output, so no matter if you use the MIN or MAX (or, in the case of numbers, AVG or SUM).
-
Hello, I'm looking to create a sub query to display certain information. On the form that the information is entered, the user has the option to enter a phone number extension, as appropriate. If this is the case, I want the phone number to show as 555-867-5309 (x 1234). However, without the problem of controls, the (x) will be displayed without worrying and seems sloppy. Here is the code I have, please notify.
There will be two places, it will be necessary - for the telephone number of the applicant and the app (SME) contact information manager.
Thank you.
select pm.pk_proj_master_id "Project Number", pm.trackit_work_order "TrackIt Work Order", pm.name "Project Name", pm.status "Project Status", req.last_name||', '||req.first_name||', '||req.middle_initial||'.' "Requestor Name", rde.department_group_descr "Requestor Department Name", req.department_descr "Requestor Division Name", pm.requester_ext, case when pm.requester_ext in ( select pm.requester_phone|| '(x'||pm.requester_ext ||')' "Requesters Number" from protrac_master pm where pm.requester_ext is not null ) else ( select pm.requester_phone "Requesters Number" from protrac_master pm ) end as "Requester Number", man.last_name||', '||man.first_name||', '||man.middle_initial||'.' "SME Name", mdg.department_group_descr "SME Department Name", man.department_descr "SME Division Name", pm.app_manager_ext, case when pm.app_manager_ext in ( select pm.app_manager_phone|| '(x'||pm.app_manager_ext ||')' "SME Number" from protrac_master pm where pm.app_manager_phone is not null ) else ( select pm.app_manager_phone "SME Number" from protrac_master pm ) end as "Requester Number", pm.createby_date "Date Entered", pm.date_begin "Date Began", pm.date_completed "Date Completed", pm.estimated_date "Estimated Completion Date" from protrac_master pm, cobr.vw_pps_payroll req, cobr.department_group rde, cobr.vw_pps_payroll man, cobr.department_group mdg where pm.requester_id = req.emple_no and pm.requester_dept_id = rde.pk_department_group_id and pm.app_manager_id = man.emple_no and pm.app_manager_dept_id = mdg.pk_department_group_id order by pm.pk_proj_master_id
I think you can avoid the sub query thing simply by using the NVL2 function:
select ... , NVL2( pm.requester_ext , pm.requester_phone|| '(x'||pm.requester_ext ||')' , pm.requester_phone) "Requesters Number" ... , NVL2( pm.app_manager_ext , pm.app_manager_phone|| '(x'||pm.app_manager_ext ||')' , pm.app_manager_phone) "Manager Number" ... from protrac_master pm , ...
-
Problem with the simple query.
Hi all
I am facing problem with the query below
Select A.COL1, A.COL2
B.COL1, B.COL2
FROM TABLE1 A
TABLE 1 B
WHERE A.header = '123'
AND B.header = '123'
AND nvl (A.COL6, 'ABC') = 'ABC '.
AND NVL (B.COL6, 'DEF') = 'DEF '.
Basically, my requiremenyt is: I have only one table, TABLE1 here, which has a line two lines (for the same header) as "ABC" and another is "DEF". Table 1 has two columns (col1, col2) that should be displayed for both lines.
When the header has two records in table1 top query works. and but if I do not have a record for any header example there are a record for "abc" in col6 only. so my query above does not work because there is no record for 'DEF' in col6. But I want to again request to fecth the output (for b.col1 and b.col2 should have null values)
could you pls suggest me how to get the 4 columns.
Thanks in advance
Kind regards
UVA.
Try to place the status of outer join on column: analytical_criterion_code as
and nvl (AUDIT.analytical_criterion_code, 'AUDIT2') = 'verification2. '
.
.
and nvl (TRANS.analytical_criterion_code, 'TRANS2') = 'TRANS2.
In the sub query based on the opinions that you have given in post # 1, although there is no value "DEF * ' for col6 due to the condition of outer join on b.col6 (+) line is extracted with b.col [1,2,3] as NULL values. Try to remove the (+) sign b.col6 and test.
with t as)
Select 111 col1, col2 'aaa', 'ABC' col6 123 header of all the double union
Select 222 'bbb', 'DEF' col6, 123 double header
)
q as (select 123 double header)
Select A.COL1, A.COL2, A.COL6
B.COL1, B.COL2, b.COL6
q.header
T a
t b
q
where a.col6 (+) = 'ABC '.
and b.col6 (+) = "DEF."
and q.header = a.header (+)
and q.header = b.header (+)
-
ORDER BY in the subselect, then a join
I had a difficult time in the research on this or even prove it so I came to the forum asking for advice.
My question is how Oracle will take care of the scheduling of a query in which I
SELECT * FROM ( SELECT * FROM ( SELECT LEVEL c1, LEVEL * TRUNC(DBMS_RANDOM.VALUE(1, 4)) val_rnd FROM DUAL CONNECT BY LEVEL <= 200) ORDER BY c1 ASC) a, ( SELECT TRUNC( LEVEL * DBMS_RANDOM.VALUE(1, 4)) val_rnd2 FROM DUAL CONNECT BY LEVEL <= 200) b WHERE a.c1 = b.val_rnd2(+)
In this case, my subselect is the order of the ascendants of c1. That part I understand, and I'll do my subquery 'a' ordered to become. My next step then joins this request sorted to a second table ('b').
In this join, Oracle always preserves my initial sort or do I need to add a second order by a.C1 ASC after the join to guarantee that she will return in a sorted order.
My example above returns the query how I want that it but I can't tell if it's just because of me be lucky and Oracle return correctly or if it will be guaranteed 100% function this way.
I'm running on Oracle 11.2.0.4
Oracle can transform your query into something that is easier to optimize, but with the same semantics. Being the ORDER BY in a view online, I guess that Oracle could even decide to ignore it (although I'm not sure of this point) - as Justin and Frank write already: only an ORDER BY in the main query will give you the 100% guarantee. If I run your query to 11.2.0.1 plan is:
----------------------------------------------------------------------------------------
| ID | Operation | Name | Lines | Bytes | Cost (% CPU). Time |
----------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1. 39. 6 (34) | 00:00:01 |
| 1. SORT ORDER BY | | 1. 39. 6 (34) | 00:00:01 |
|* 2 | OUTER HASH JOIN | | 1. 39. 5 (20) | 00:00:01 |
| 3. VIEW | | 1. 26. 2 (0) | 00:00:01 |
|* 4 | CONNECT TO WITHOUT FILTERING. | | | | |
| 5. QUICK DOUBLE | | 1. | 2 (0) | 00:00:01 |
| 6. VIEW | | 1. 13. 2 (0) | 00:00:01 |
|* 7 | CONNECT TO WITHOUT FILTERING. | | | | |
| 3 × QUICK DOUBLE | | 1. | 2 (0) | 00:00:01 |
----------------------------------------------------------------------------------------
Information of predicates (identified by the operation identity card):
---------------------------------------------------
2 - access("from$_subquery$_002".") C1 '=' B '. "VAL_RND2" (+)) "
4 filter (LEVEL<>
7 filter (LEVEL<>
So we can see that Oracle made a transformation and moved the SORT ORDER BY in subquery: with this plan, you get the correct order - but there is no guarantee that the Oracle will use this plan (and transformation) in different versions / with different settings etc.
-
Need to use values from the first query in other queris to the data model
Hello
Here is my requirement-
I use the data model to run multiple queries. The first query, I get 10 records. Now, I want to use these 10 records in the second query to get my final result. I am not able to use the sub query as the two motions are quite long and complex.
Select distinct Bishop of emp
Select empno, emp where Bishop in (: Bishop)
I can't use: Bishop because it will give only the last value stored at Archbishop. Is it possible to be able to use all the values from the first query in the second query using the data model?Hello
Are you sure that you have your "dataStructure" configured correctly? Try this simple example:
Hope this helps
Andy
-
Hello
I created a sub with sorting on a column request. (I have cutomized the IKM control append for order). I see the order by the State. If I use this (interface yellow) subquery in the main query (is also yellow interface) I do not see the order of condition
Subquery (Q-yellow interface):
Select
NEST,
START_TIME,
ACTION_TYPE_CODE
Of
(
SELECT DISTINCT
SERVICE_TRACKING_S.PID PID,
START_TIME TO_TIMESTAMP (TO_CHAR (SERVICE_TRACKING_S.ACTION_TIME, 'DD-MON-YY HH24:MI:SS'), "MON-DD-YY HH24:MI:SS"),
SERVICE_TRACKING_S.ACTION_TYPE_CODE ACTION_TYPE_CODE
of KSTGDB. SERVICE_TRACKING_S SERVICE_TRACKING_S
where (1 = 1)
ORDER BY-----------------------------------------------
NEST
START_TIME CSA
)
ODI_GET_FROM
Main query (Q1 - yellow interface):
Select
NEST,
START_TIME,
ACTION_TYPE_CODE,
RN,
RN_MAX
CEN
Select
Q.PID PID,
Q.START_TIME START_TIME,
WHEN Q.START_TIME - LAG(Q.START_TIME,1,Q.START_TIME) CASE above (PARTITION OF Q. PID ORDER OF Q.START_TIME) > numtodsinterval(75,'minute')
or Q.PID! = LAG (Q.PID, 1, 0) ON (Q.PID ORDER OF Q.START_TIME PARTITION) THEN 1 OTHER Q.ACTION_TYPE_CODE END ACTION_TYPE_CODE.
ROW_NUMBER() OVER(PARTITION BY Q.PID ORDER BY Q.START_TIME) RN,
Count (*) over (PARTITION OF Q.PID ORDER OF Q.START_TIME LINES BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
RN_MAX
de)
SELECT DISTINCT
SERVICE_TRACKING_S.PID PID, START_TIME TO_TIMESTAMP (TO_CHAR (SERVICE_TRACKING_S.ACTION_TIME, 'DD-MON-YY HH24:MI:SS'), "MON-DD-YY HH24:MI:SS"), SERVICE_TRACKING_S.ACTION_TYPE_CODE ACTION_TYPE_CODE
of KSTGDB. SERVICE_TRACKING_S SERVICE_TRACKING_S
where (1 = 1)
-I don't get stopped by here-
) Q
where (1 = 1)
) ODI_GET_FROM
Thanks in advance
KHello
what you trying to do? A decree by a subselect in the useless statement.
Also use an order you need to add an option and change the IKM
-
FETCH ONE RECORD IN THE SECOND TABLE OF CORRELATED SUB QUERY
Hi all
I have provided the script below, I want to single fecth record in the second table in the join query,
based on the example below, I want to go get one record of the table emp2 what matches with the emp_id of table emp1, please note emp2 may contain more record for the emp_id emp1 which respects
all records can be selected in the table emp2.
DROP TABLE emp1.
CREATE TABLE emp1 (emp_id NUMBER);
INSERT INTO emp1 VALUES (1);
INSERT INTO emp1 VALUES (2);
COMMIT;
DROP TABLE emp2.
CREATE TABLE emp2 (emp_id NUMBER, emp_name VARCHAR2 (100));
INSERT INTO emp2 VALUES (1, 'Name1');
INSERT INTO emp2 VALUES (2, 'Name2');
INSERT INTO emp2 VALUES (1, 'Name3');
INSERT INTO emp2 VALUES (2, 'Conjoint4');
COMMIT;
SELECT * from emp1.
SELECT * from emp2.
SELECT T1. EMP_ID, MIN (T2. EMP_NAME)
FROM EMP1, EMP2 T2 T1
WHERE T1. EMP_ID = T2. EMP_ID
GROUP T1. EMP_ID;
My output should be the same as the result set of query above, but I don't want this logic, please provide the solution by using a different logic, thanks in advance.
2811876 wrote:
Thanks for your comments :-)
My business logic will change to 'Fetch N second timeline table', that's the reason why I asked for a different approach, if I use max, min to achieve this does not allow me to evolve dynamically.
Although logic has not been expressed at all in your original question, so good job I asked.
You could do something like:
SQL > ed
A written file afiedt.buf1 with emp1 (select 1 as the emp_id of union double all the)
2. Select 2 double
3 )
4, emp2 (select 1 as emp_id, 'name 1' as emp_name double union all
5. Select "name 2' Union double every 2
6 select 1, 'name' 3' from dual union all
7. Select 2, 'name 4' double union all.
8 select 1, 'name 5' from dual union all '.
9 select 2, 'name 6' from dual '.
10 )
11-
12. end of test data
13-
14 select emp_id, emp_name
15 of)
16 select t1.emp_id, t2.emp_name
17, row_number() over (partition by order of t2.emp_name t1.emp_id) rn
emp1 t1 18
19 join t2 emp2 (t1.emp_id = t2.emp_id)
20 )
21 * where rn<=>=>
SQL > /.Enter the value for rows_required: 1
21 Alumni: where rn<=>=>
21 news: where rn<=>=>EMP_ID EMP_NA
---------- ------
1 name 1
2 name 2SQL > /.
Enter the value for rows_required: 2
21 Alumni: where rn<=>=>
21 news: where rn<=>=>EMP_ID EMP_NA
---------- ------
1 name 1
1 name 3
2 name 2
2 name 4 -
How to preset the order of the lines in the outer query of a correlated query?
Hello
I have the following simple query:
Who calculates a difference running and uses «row_number() over (...)» which is a specific feature of the Oracle to do it. We get the following result (that we will consider correct):select empno, ename, sal, sum(case when rn = 1 then sal else -sal end) over (order by sal, empno) as running_diff from ( select empno, ename, sal, row_number() over (order by sal, empno) as rn from emp where deptno = 10 );
I wanted to arrive at a different solution from the solution, it was not a specific Oracle . I tried the following code:EMPNO ENAME SAL RUNNING_DIFF ---------- ---------- ---------- ------------ 7934 MILLER 1300 1300 7782 CLARK 2450 -1150 7839 KING 5000 -6150
(EDIT: after further thought, this code is entirely different sense and will never get closer, the result above.) Considers that it is wrong and ignore this attempt.)
but the result isselect a.empno, a.ename, a.sal, (select case when a.empno = min(b.empno) then sum(b.sal) else sum(-b.sal) end from emp b where b.empno <= a.empno and b.deptno = a.deptno) as running_diff from emp a where a.deptno = 10;
that is a long way from the initial result. I tried everything I could think to order lines before running difference is calculated, but were unsuccessful.EMPNO ENAME SAL RUNNING_DIFF ---------- ---------- ---------- ------------ 7782 CLARK 2450 2450 7839 KING 5000 -7450 7934 MILLER 1300 -8750
Is there a way to change this second request-(without using Oracle specific features) - without the help of windowing functions that give the same result as the first query?
Rephrase the question above:
Is it possible, using plain vanilla SQL (which is the aggregate functions and operations such as joins and unions) to create a query that produces the same result as the first?
In addition, it is not for production code. It's just an exercise in manipulation set I would like to see a solution for.
Thank you for your help,
John.
Published by: 440bx - 11 GR 2 on July 18, 2010 12:50 AM - correct ' ho w "to"how ".
Published by: 440bx - 11 GR 2 on July 18, 2010 01:42 - struck all references to row_number and windowing being features of Oracle functions.
Published by: 440bx - 11 GR 2 on July 18, 2010 03:51 - pointed out that my essay is terribly wrong and it had reaffirmed the goal to make it clearer.Hi, John,.
A way to get a total operating (which is essentially what you want) must make a self-join. Join each line (let's call it the current line, or c) for himself and everything that preceded it (call this the previous line or p), and do a regular lump SUM, like this:
WITH got_base_sal AS ( SELECT deptno , 2 * MIN (sal) AS base_sal FROM scott.emp GROUP BY deptno ) SELECT c.deptno , c.empno , c.ename , c.sal , b.base_sal - SUM (p.sal) AS running_diff FROM scott.emp c JOIN scott.emp p ON c.deptno = p.deptno AND ( c.sal > p.sal OR ( c.sal = p.sal AND c.empno >= p.empno ) ) JOIN got_base_sal b ON c.deptno = b.deptno WHERE c.deptno IN (10) GROUP BY c.deptno , c.empno , c.ename , c.sal , b.base_sal ORDER BY c.deptno , running_diff DESC ;
Output:
DEPTNO EMPNO ENAME SAL RUNNING_DIFF ---------- ---------- ---------- ---------- ------------ 10 7934 MILLER 1300 1300 10 7782 CLARK 2450 -1150 10 7839 KING 5000 -6150
I said you basically want a total runninng. There are two differences between a cumulative and your needs
(1) you want to have a total of the negation of what is in the table. That's trivial: use a sign less.
(2) you want the first point to count as positive rather than negative. It's not so trivial. The above query counts all know as negative, but adds an offset to make it appear as if the first item had been posted as a positive, not negative result.You don't say what you want to do in the case of a tie (two or more lines having the same sal). The above query uses empno as a tiebreaker, so all sals are calculated as if they were separate. This is similar to what the analytical functions do when the window comes from the ranks. If you want something similar to windowing by scope, which could actually be simpler.
The above query calculates a running_diff separate for each deptno, similar to "PARTITION BY deptno" in analytic functions. You happen be interested in a single deptno right now, but you can change the WHERE clause of the main query, or to omit, and the query still works. If you don't want this feature (analagoud for not having any PARTITION BY), it is easy to change the query.
You can also get these results by using a WITH recursive clause. Which meets the criteria to avoid analytical functions and features specific to Oracle, but not on the use of the only clear and simple SQL features.
-
Performance of the queries in order to get the most recent price
Happy new year everyone.
I have a table of price in my system that has several awards for each product with the date, the price is entered into force.
I have queries throughout the system to retrieve the most recent actual price for the date of the transaction.
I can find to implement the easiest way is to have a user-defined function to collect the prize.
My problem is that many of my questions have access to large amounts of data (for example, transactions) and my table of prices is also big enough - both have millions of records. Using a Pl/SQL function defined by the user in my query, I get a lot of switching context between SQL and PL/SQL and my questions are not well
Here is an example of code, which simplifies my scenario:
drop table xo_stock_trans; create table xo_stock_trans (item varchar2(25), trans_date date, quantity number(20,4)); insert into xo_stock_trans values('A',TO_DATE('25-DEC-2014','DD-MON-YYYY'), 4); insert into xo_stock_trans values('A',TO_DATE('27-DEC-2014','DD-MON-YYYY'), -2); insert into xo_stock_trans values('A',TO_DATE('28-DEC-2014','DD-MON-YYYY'), 5); insert into xo_stock_trans values('B',TO_DATE('23-DEC-2014','DD-MON-YYYY'), 20); insert into xo_stock_trans values('B',TO_DATE('26-DEC-2014','DD-MON-YYYY'), -6); insert into xo_stock_trans values('B',TO_DATE('29-DEC-2014','DD-MON-YYYY'), 15); / -- Generate lots more data BEGIN -- Generate more trans dates for r in 1..1000 LOOP insert into xo_stock_trans select item, trans_date - r - 7 as trans_date, ROUND(dbms_random.value(1,50),2) as quantity from xo_stock_trans where trans_date between TO_DATE('23-DEC-2014','DD-MON-YYYY') AND TO_DATE('29-DEC-2014','DD-MON-YYYY') and item in ('A','B'); END LOOP; COMMIT; -- generate more items for lt in 1..12 LOOP -- generate C,D, E, items INSERT into xo_stock_trans SELECT chr(ascii(item)+(lt*2)) as item, trans_date, quantity from xo_stock_trans where item in ('A','B'); -- generate A1, A2, B1, B2, etc for nm in 1..10 LOOP INSERT INTO xo_stock_trans select item || to_char(nm), trans_date, quantity from xo_stock_trans where length(item) = 1; END LOOP; COMMIT; END LOOP; COMMIT; END; / create index xo_stock_trans_ix1 on xo_stock_trans (item); create index xo_stock_trans_ix2 on xo_stock_trans (trans_date); exec dbms_stats.gather_table_stats(ownname =>user, tabname => 'XO_STOCK_TRANS' , estimate_percent => 100, degree => dbms_stats.auto_degree, cascade=>true); / drop table xo_prices; create table xo_prices (item varchar2(25), price_date date, gross_price number(20,4), net_price number(20,4), special_price number(20,4) ); insert into xo_prices values ('A', to_date('01-DEC-2014','DD-MON-YYYY'), 10, 8, 6); insert into xo_prices values ('A', to_date('25-DEC-2014','DD-MON-YYYY'), 9, 8, 6); insert into xo_prices values ('A', to_date('26-DEC-2014','DD-MON-YYYY'), 7, 6, 4); insert into xo_prices values ('B', to_date('01-DEC-2014','DD-MON-YYYY'), 5.50, 4.50, 3); insert into xo_prices values ('B', to_date('25-DEC-2014','DD-MON-YYYY'), 5.00, 4.00, 3); insert into xo_prices values ('B', to_date('26-DEC-2014','DD-MON-YYYY'), 3.50, 2.50, 2); / -- Generate lots more data BEGIN -- Generate more price dates for r in 1..1000 LOOP insert into xo_prices select item, price_date - r - 7 as price_date,gross_price, net_price, special_price from xo_prices where price_date between TO_DATE('23-DEC-2014','DD-MON-YYYY') AND TO_DATE('29-DEC-2014','DD-MON-YYYY') and item in ('A','B'); END LOOP; COMMIT; -- generate more items for lt in 1..12 LOOP -- generate C,D, E, items INSERT into xo_prices SELECT chr(ascii(item)+(lt*2)) as item, price_date, gross_price + (lt*2), net_price + (lt*2), special_price + (lt*2) from xo_prices where item in ('A','B'); -- generate A1, A2, B1, B2, etc for nm in 1..10 LOOP INSERT INTO xo_prices select item || to_char(nm), price_date, gross_price, net_price, special_price from xo_prices where length(item) = 1; END LOOP; COMMIT; END LOOP; END; / create index xo_prices_ix1 on xo_prices (item, price_date); exec dbms_stats.gather_table_stats(ownname =>user, tabname => 'XO_PRICES' , estimate_percent => 100, degree => dbms_stats.auto_degree, cascade=>true); / create or replace function xo_get_price(I_Item in VARCHAR2, I_Date in DATE, i_Price_type IN VARCHAR2) RETURN NUMBER IS -- Function to get most recent effective price prior to the date CURSOR c_get_prices(P_Item VARCHAR2, P_Date VARCHAR2) IS SELECT gross_price, net_price, special_price FROM XO_PRICES WHERE item = P_Item AND price_date <= P_Date ORDER BY price_date desc; -- most recent price l_gross_price NUMBER(20,4); l_net_price NUMBER(20,4); l_special_price NUMBER(20,4); BEGIN OPEN c_get_prices(I_Item, I_Date); FETCH c_get_prices INTO l_gross_price, l_net_price, l_special_price; CLOSe c_get_prices; IF I_Price_Type='GROSS' then return l_gross_price; ELSIF I_Price_Type= 'NET' then return l_net_price; ELSIF I_Price_Type= 'SPECIAL' then return l_special_price; END IF; END xo_get_price; / -- Here is a typical query I am trying to perform select tr.item, tr.trans_date, tr.quantity , xo_get_price(tr.item, tr.trans_date, 'GROSS') as gross_price , xo_get_price(tr.item, tr.trans_date, 'NET') as net_price , xo_get_price(tr.item, tr.trans_date, 'SPECIAL') as special_price from xo_stock_trans tr where tr.trans_date between '01-AUG-2014' and '31-AUG-2014';
I would like to refactor my request so that I do not use the user Pl/SQL functions, but so far I can't get something that works better than the SQL above. For example, the following query is MUCH longer:
select tr.item, tr.trans_date, tr.quantity , pr.gross_price , pr.net_price , pr.special_price from xo_stock_trans tr join xo_prices pr on pr.item = tr.item and pr.price_date = (select max(pr2.price_date) from xo_prices pr2 where pr2.item = pr.item and pr2.price_date <= tr.trans_date ) where tr.trans_date between '01-AUG-2014' and '31-AUG-2014';
I'm interested to know if anyone has addressed a similar scenario and have managed to write more efficient code.
I looked at the determinism/manual caching of the function, but the article/date combinations are quite unique and therefore he does not benefit from him.
Any suggestion under review - parallelism, analytical, pipeline functions, etc.
Alan
Hi, Alan.
Alan Lawlor wrote:
...
My problem is that many of my questions have access to large amounts of data (for example, transactions) and my table of prices is also big enough - both have millions of records. Using a Pl/SQL function defined by the user in my query, I get a lot of switching context between SQL and PL/SQL and my questions are not well...
You got that right! User-defined functions can be very practical, but this practice comes with a price.
What version of Oracle are you using? The Oracle 12, there is a new feature of 'temporal validity' which may help you.
In any version, it will be much faster if you add a new column to the xo_prices table. You can call this end_date, although it would in fact be the date when some other prices took effect. You might put DATE' 9999-12-31 in the column end_date for current prices. You can calculate end_date using the analytical function of LEAD. Be sure to re-calcluate end_date when you insert new rows into xo_prices, or when you update the dates on existing lines.
Once you have PRICE_DATE and end_date in the XO_PRICES table, you can join this table to get the real price from d by including
AND d > = xo_prices.price_date
AND d< > >
in the join condition.
In some situations, especially when you don't have much different (item, dates) combinations, scalar-sub-queries could be faster than joins.
Whatever it is, it participates without PL/SQL, so there is no context switching.
-
How to know what sub query returns multiple rows
Hi all
Someone can give me hints, how to know what sub query returns many rows in the following query.
Kind regards/* Formatted on 2011/05/17 19:22 (Formatter Plus v4.8.8) */ SELECT a.*, ROWNUM AS rnm FROM (SELECT DISTINCT '1' AS "Page View", ou.org_unit_name AS "Org", prxm.mbr_idntfr AS "Beneficiary ID", md.last_name || ', ' || md.first_name AS "Beneficiary Name", pci.idntfr AS "Tracking No.", TO_CHAR (TRUNC (req.pa_rqst_date), 'MM/dd/yyyy' ) AS "Request Date", sts.status_name AS "Status", req.pa_rqst_sid AS "Request #", prxm.mbr_sid AS "Mbr_sid", TO_CHAR (TRUNC (req.pa_revision_date), 'MM/dd/yyyy' ) AS "Last Updated", TO_CHAR (psd.TO_DATE, 'MM/dd/yyyy') AS "TO_DATE", prxpl.prvdr_lctn_iid AS "PRVDR_LCTN_IID", pd.prvdr_sid AS "PRVDR_SID", 'Y' AS "State View", DECODE ((SELECT DISTINCT pd.national_prvdr_idntfr FROM pa_request_x_provider_location prxplo WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid AND prxplo.oprtnl_flag = 'A' AND prxplo.pa_prvdr_type_lkpcd = 'RR'), 0, (SELECT prxplo.prvdr_lctn_idntfr FROM pa_request_x_provider_location prxplo WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid AND prxplo.oprtnl_flag = 'A' AND prxplo.pa_prvdr_type_lkpcd = 'RR'), NULL, (SELECT prxplo.prvdr_lctn_idntfr FROM pa_request_x_provider_location prxplo WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid AND prxplo.oprtnl_flag = 'A' AND prxplo.pa_prvdr_type_lkpcd = 'RR'), (SELECT DISTINCT pd.national_prvdr_idntfr FROM pa_request_x_provider_location prxplo WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid AND prxplo.oprtnl_flag = 'A' AND prxplo.pa_prvdr_type_lkpcd = 'RR') ) AS "NPI/ID", DECODE ((SELECT pd.org_bsns_name FROM pa_request_x_provider_location prxplo WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid AND prxplo.oprtnl_flag = 'A' AND prxplo.pa_prvdr_type_lkpcd = 'RR'), NULL, (SELECT pd.last_name || ', ' || pd.first_name || ' ' || pd.middle_name FROM pa_request_x_provider_location prxplo WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid AND prxplo.oprtnl_flag = 'A' AND prxplo.pa_prvdr_type_lkpcd = 'RR'), (SELECT pd.org_bsns_name FROM pa_request_x_provider_location prxplo WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid AND prxplo.oprtnl_flag = 'A' AND prxplo.pa_prvdr_type_lkpcd = 'RR') ) AS "Prvdr Name", TO_CHAR (psd.from_date, 'MM/dd/yyyy' ) AS "Srvc From Date", TO_CHAR (req.validity_start_date, 'MM/DD/YYYY' ) AS "Due Date", (fn_get_busniess_days (TRUNC (req.validity_start_date)) ) AS "Days<br>Left", req.pa_mode_type_lkpcd AS "Source", TO_CHAR (TRUNC (wmdtl.rtng_date), 'MM/dd/yyyy' ) AS "Assigned On", NVL (wmdtl.assigned_to_user_name, 'Not Assigned' ) AS "Assigned To", req.org_unit_sid AS "OrgUnitSid", TO_CHAR (wmdtl.modified_date, 'MM/dd/yyyy hh24:mi:ss' ) AS "WTRD_MODIFIED_DATE", TO_CHAR (wmdtl.rtng_date, 'MM/dd/yyyy' ) AS "WTRD_RTNG_DATE", req.status_cid AS "PA_STATUS_CID", TO_CHAR (req.modified_date, 'MM/dd/yyyy' ) AS "PA_REQ_MODIFIED_DATE", prs.state_pa_srvc_type_code AS "STATE_PA_SRVC_TYPE_CODE", wmdtl.wm_pa_task_rtng_dtl_sid AS "WM_TASK_RTNG_DTL_SID", wmdtl.assigned_to_user_acct_sid AS "WTRD_Assigned_to_user_acct_sid", (fn_get_busniess_days (TRUNC (req.validity_start_date)) ) AS "Days<br>LeftSort", wmdtl.assigned_to_org_unit_sid AS "WTRD_Assigned_to_OrgUntSid", DECODE ((SELECT COUNT (*) FROM pa_request_status prs WHERE prs.pa_rqst_sid = req.pa_rqst_sid AND prs.status_cid = 5 AND prs.oprtnl_flag = 'I'), 0, 'N', 'Y' ) AS "SHOW_UTILIZATION" FROM pa_request req, pa_certification_identifier pci, status sts, pa_request_x_member prxm, wm_pa_task_routing_detail wmdtl, pa_service_date psd, org_unit ou, pa_request_service prs, pa_request_x_provider_location prxpl, provider_location pl, provider_detail pd, provider p, mbr_dmgrphc md WHERE req.oprtnl_flag = 'A' AND req.status_cid NOT IN (20, 30, 70, 25, 80, 96, 85, 5, 97, 98, 101) AND req.org_unit_sid IN (3057, 3142, 3058, 3143, 3059, 3144, 3060, 3145, 3061, 3146, 3062, 3147, 3063, 3148, 3064, 3149, 3065, 3150, 3066, 3151, 3067, 3152, 3068, 3153, 3069, 3154, 3070, 3155, 3071, 3156, 3072, 3157, 3073, 3158, 3074, 3159, 3075, 3160, 3076, 3161, 3077, 3162, 3078, 3163, 3079, 3164, 3080, 3165, 3081, 3166, 3082, 3167, 3083, 3168, 3084, 3169, 3085, 3170, 3086, 3171, 3087, 3172, 3088, 3173, 3089, 3174, 3090, 3175, 3091, 3176, 3092, 3177, 3093, 3178, 3094, 3179, 3095, 3180, 3096, 3181, 3097, 3182, 3098, 3183, 3099, 3184, 3100, 3185, 3101, 3186, 3102, 3187, 3103, 3003, 75000104, 75000108, 2006, 75000103, 75000102, 75000113, 75000111, 75000109, 2001, 2009, 75000105, 75000107, 2004, 2010, 2013, 2014, 2005, 2011, 75000112, 2002, 1001, 2012, 75000106, 2007, 75000101, 2003, 75000110, 2008, 3001, 3002, 3019, 3104, 3020, 3105, 3021, 3106, 3022, 3107, 3023, 3108, 3024, 3109, 3025, 3110, 3026, 3111, 3027, 3112, 3028, 3113, 3029, 3114, 3030, 3115, 3031, 3116, 3032, 3117, 3033, 3118, 3034, 3119, 3035, 3120, 3036, 3121, 3037, 3122, 3038, 3123, 3039, 3124, 3040, 3125, 3041, 3126, 3042, 3127, 3043, 3128, 3044, 3129, 3045, 3130, 3046, 3131, 3047, 3132, 3048, 3133, 3049, 3134, 3050, 3135, 3051, 3136, 3052, 3137, 3053, 3138, 3054, 3139, 3055, 3140, 3056, 3141) AND req.pa_rqst_sid = prs.pa_rqst_sid AND prs.oprtnl_flag = 'A' AND prs.pa_rqst_srvc_sid = psd.pa_rqst_srvc_sid AND psd.oprtnl_flag = 'A' AND req.pa_rqst_sid = pci.pa_rqst_sid AND pci.oprtnl_flag = 'A' AND req.pa_rqst_sid = prxm.pa_rqst_sid AND prxm.oprtnl_flag = 'A' AND md.oprtnl_flag = 'A' AND md.status_cid = 2 AND TRUNC (SYSDATE) BETWEEN md.from_date AND md.TO_DATE AND prxm.mbr_sid = md.mbr_sid AND ou.org_unit_sid = req.org_unit_sid AND ou.oprtnl_flag = 'A' AND req.pa_rqst_sid = prxpl.pa_rqst_sid AND prxm.pa_rqst_sid = prxpl.pa_rqst_sid AND pci.pa_rqst_sid = prxm.pa_rqst_sid AND pci.pa_rqst_sid = wmdtl.subsystem_task_sid AND pci.pa_rqst_sid = prxpl.pa_rqst_sid AND prxpl.pa_prvdr_type_lkpcd = 'RR' AND prxpl.oprtnl_flag = 'A' AND req.status_cid = sts.status_cid AND sts.status_type_cid = 3 AND sts.oprtnl_flag = 'A' AND prxpl.prvdr_lctn_iid = pl.prvdr_lctn_iid AND p.prvdr_sid = pd.prvdr_sid AND p.prvdr_sid = pl.prvdr_sid AND pd.oprtnl_flag = 'A' AND pd.status_cid = 2 AND TRUNC (SYSDATE) BETWEEN pd.from_date AND pd.TO_DATE AND wmdtl.subsystem_task_sid = req.pa_rqst_sid AND wmdtl.subsystem_lkpcd = 'PA' AND wmdtl.oprtnl_flag = 'A' AND req.pa_rqst_date > (SYSDATE - 365) ORDER BY TO_DATE ("Request Date", 'MM/dd/yyyy hh24:mi:ss') DESC, "Beneficiary Name" ASC) a WHERE ROWNUM < 102;
Prakash P
Published by: BluShadow on May 17, 2011 15:01
addition of {noformat}{noformat} tags around the code
3360 wrote:
See point 9 of this section of the FAQ on how to format the code.I see that you did.
No, I did. It's pretty easy to change if the code seems formatted anyway below. It's when I go to edit the message and find no sense because it is not formatted in all cases, I despair. {noformat} :) {noformat}
-
Dynamic display of columns in the pivot query
I have a table called STUDENT_SCORE. I need to display the avarage score/month for 2 years and the monthly score until today "month.
Then assume that it is April 2009. The report will look like
Roll_id 2007avg 2008avg Jan09-Mar09 Feb 09
101 80.9 70.9 89.7 90.9 56.8
102 70.9 23.9 87.2 90.0 76.8
I tried a bit, but can't fix the monthly score display dynamically.
DDL/DML is as below
create the table STUDENT_SCORE
(number of roll_id,
date of mth_id,
The partition number);
insert into STUDENT_SCORE values
(101, to_date (January 1, 2006 ', ' dd/mm/yyyy'), 67.5);
insert into STUDENT_SCORE values
(101, to_date (February 1, 2006 ', ' dd/mm/yyyy'), 77.5);
insert into STUDENT_SCORE values
(101, to_date (March 1, 2006 ', ' dd/mm/yyyy'), 87.5).
insert into STUDENT_SCORE values
(101, to_date (April 1, 2006 ', ' dd/mm/yyyy'), 27.5);
insert into STUDENT_SCORE values
(101, to_date (May 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (June 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (July 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (August 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (September 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (October 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (November 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (December 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (January 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (February 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (March 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (April 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (May 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (June 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (July 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (August 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (September 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (October 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (November 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (December 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (1 January 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (February 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (March 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (April 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (May 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (June 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (July 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (August 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (September 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (October 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (November 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (December 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (January 1, 2009 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (January 1, 2006 ', ' dd/mm/yyyy'), 67.5);
insert into STUDENT_SCORE values
(102, to_date (February 1, 2006 ', ' dd/mm/yyyy'), 77.5);
insert into STUDENT_SCORE values
(102, to_date (March 1, 2006 ', ' dd/mm/yyyy'), 87.5).
insert into STUDENT_SCORE values
(102, to_date (April 1, 2006 ', ' dd/mm/yyyy'), 27.5);
insert into STUDENT_SCORE values
(102, to_date (May 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (June 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (July 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (August 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (September 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (October 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (November 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (December 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (January 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (February 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (March 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (April 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (May 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (June 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (July 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (August 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (September 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (October 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (November 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (December 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (1 January 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (February 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (March 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (April 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (May 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (June 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (July 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (August 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (September 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (October 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (November 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (December 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (January 1, 2009 ', ' dd/mm/yyyy'), 57.5);Hello
The script below produces what you want (as far as I can tell, without your desired results).
Student_score_smry subquery Gets the year and monthly averages of student_score.
It is completely static: it always produces 11 monthly columns (from January to November) and the names of columns hardcoded (m01 through m11).
For dynamic column names you need, I used SQL * COLUMN more orders.
To get the variable number of monthly columns you need, SELECT from the main query clause uses a script under (dynamic_month.sql) to only show the correct number (which can be 0).The student_score_wk_smry of subquery retrieves the weekly averages of the student_score_wk.
He, too, is completely static: it always produces 6 weekly columns with names hardcoded (w1 through w6).There are four preliminary motions, that write two scripts under:
Prelimiary C1, C2 and C3 queries write orders of COLUMN for annual, monthly and weekly columns in dynamic_columns.sql
Preliminary motion M written between 0 and 11 items in SELECT-clause in sub-script dynamic_month.sqlThe main script is:
SET FEEDBACK OFF SET LINESIZE 200 SET PAGESIZE 0 SET VERIFY OFF SPOOL dynamic_column.sql -- Preliminary query C1: Columns for last 2 years SELECT 'COLUMN y' || LEVEL || ' HEADING "' || TO_CHAR ( ADD_MONTHS ( &target_month , 12 * (-3 + LEVEL) ) , 'YYYY' ) || 'avg"' FROM dual CONNECT BY LEVEL <= 2 ; -- Preliminary query C2: 11 prior months in this year SELECT 'COLUMN m' || TO_CHAR (LEVEL, 'fm00') || ' HEADING "' || TO_CHAR ( ADD_MONTHS ( TRUNC (&target_month, 'YYYY') , LEVEL - 1 ) , 'MonYY' ) || '"' FROM dual CONNECT BY LEVEL <= 11 ; -- Preliminary query C3: 6 weeks before target_month WITH got_w_num AS ( SELECT SUBSTR (week_desc, 1, 6) AS mon_dd , ROW_NUMBER () OVER ( ORDER BY week_id DESC ) AS w_num FROM week WHERE TO_DATE (week_desc, 'Mon DD, YYYY') < &target_month ) SELECT 'COLUMN w' || TO_CHAR (7 - w_num) || ' HEADING "Week of ' || mon_dd || '"' FROM got_w_num WHERE w_num <= 6 ORDER BY w_num DESC ; SPOOL OFF -- Preliminary Query M: 0-11 months (in SELECT clause) SPOOL dynamic_month.sql SELECT ', m' || TO_CHAR (LEVEL, 'fm00') FROM dual WHERE MONTHS_BETWEEN (&target_month, TRUNC (&target_month, 'YYYY')) >= 1 CONNECT BY LEVEL <= MONTHS_BETWEEN (&target_month, TRUNC (&target_month, 'YYYY')) ; SPOOL OFF -- Restore SQL*Plus features suppressed earlier SET FEEDBACK ON SET LINESIZE 80 SET PAGESIZE 50 -- COLUMN Commands @dynamic_column.sql -- Main Query WITH student_score_smry AS ( SELECT roll_id , AVG (CASE WHEN TRUNC (mth_id, 'YYYY') = TRUNC (ADD_MONTHS (&target_month, -24), 'YYYY') THEN score END) AS y1 , AVG (CASE WHEN TRUNC (mth_id, 'YYYY') = TRUNC (ADD_MONTHS (&target_month, -12), 'YYYY') THEN score END) AS y2 , AVG (CASE WHEN TRUNC (mth_id, 'MM') = TRUNC (&target_month, 'YYYY') THEN score END) AS m01 , AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'), 1) THEN score END) AS m02 , AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'), 2) THEN score END) AS m03 , AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'), 3) THEN score END) AS m04 , AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'), 4) THEN score END) AS m05 , AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'), 5) THEN score END) AS m06 , AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'), 6) THEN score END) AS m07 , AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'), 7) THEN score END) AS m08 , AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'), 8) THEN score END) AS m09 , AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'), 9) THEN score END) AS m10 , AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'), 10) THEN score END) AS m11 FROM student_score GROUP BY roll_id ) , got_w_num AS ( SELECT week_id , ROW_NUMBER () OVER ( ORDER BY week_id DESC ) AS w_num FROM week WHERE TO_DATE (week_desc, 'Mon DD, YYYY') < &target_month ) , student_score_wk_smry AS ( SELECT roll_id , AVG (CASE WHEN W_NUM = 6 THEN score END) AS w1 , AVG (CASE WHEN W_NUM = 5 THEN score END) AS w2 , AVG (CASE WHEN W_NUM = 4 THEN score END) AS w3 , AVG (CASE WHEN W_NUM = 3 THEN score END) AS w4 , AVG (CASE WHEN W_NUM = 2 THEN score END) AS w5 , AVG (CASE WHEN W_NUM = 1 THEN score END) AS w6 FROM student_score_wk s JOIN got_w_num w ON s.wk_id = w.week_id WHERE w_num <= 6 GROUP BY roll_id ) SELECT NVL (ss.roll_id, ssw.roll_id) AS roll_id , y1, y2 @dynamic_month.sql , w1, w2, w3, w4, w5, w6 FROM student_score_smry ss FULL OUTER JOIN student_score_wk_smry ssw ON ss.roll_id = ssw.roll_id ORDER BY roll_id ;
Sub-script dynamic_column.sql might look like this:
COLUMN y1 HEADING "2007avg" COLUMN y2 HEADING "2008avg" COLUMN m01 HEADING "Jan09" COLUMN m02 HEADING "Feb09" COLUMN m03 HEADING "Mar09" COLUMN m04 HEADING "Apr09" COLUMN m05 HEADING "May09" COLUMN m06 HEADING "Jun09" COLUMN m07 HEADING "Jul09" COLUMN m08 HEADING "Aug09" COLUMN m09 HEADING "Sep09" COLUMN m10 HEADING "Oct09" COLUMN m11 HEADING "Nov09" COLUMN w1 HEADING "Week of Dec 21" COLUMN w2 HEADING "Week of Dec 28" COLUMN w3 HEADING "Week of Jan 04" COLUMN w4 HEADING "Week of Jan 11" COLUMN w5 HEADING "Week of Jan 18" COLUMN w6 HEADING "Week of Jan 25"
Other sub-script, dynamic_month.sql, might look like this:
, m01 , m02 , m03
-
"Order by" in the persistent store
Hello
I want to sort the records to permanent storage, by putting in place a query as
"Select TimeStamp in the Table where ID = + someID order by Date desc limit 0,1 '.
How can I order documents in the store and pick up the most recent date?
Help, please
Take a look around the available sorting collections - for example SimpleSortingVector.
-
Dependencies of object database by using the SQL query?
Hi guys,.
I just see the nice feature to discover the database object dependencies in the APEX (generator application-> app 123-> utilities-> database object dependencies).
Is there a way to get this dependencies just with a SQL query? Also should I calculate a process in order to get the current dependencies? In APEX, you press a calculate button before you can see the dependencies.
Thanks in advance and greetings from the Germany
Steven
After you import the app Builder application APEX 4500, I saw that the Start button the following process:
wwv_flow_theme_manager.find_object_dependencies (p_flow_id =>: fb_flow_id, p_page_id-online null);
In my example I can't use it, only the APEX_050000 user has privileges to use, and you must grant the privileges of your schema, so if you want to use it inside your application. My application must be independent of the schema and the specific database.
Also it is not recommended to use this procedure because it is one of the procedures not supported that are only used by oracle.
Maybe you are looking for
-
Can I add a button print for Thunderbird?
Is it possible to add an icon of 'button' or printer print at Thunderbird without having to click on the file or more to get to print. By example, if I see an email that I want to print it would be faster if I had a printer icon or button click.
-
Problem of eject CD-ROM XM - 50701B
This old drive that has not been used very much seems to play up. When I first start my system (SPARC SunBlade 1000) everything is fine, but when I eject the disc and it goes back, he will wait for a while then eject again and repeat this each time t
-
I so a new HP 2740. All I can say, it should come with DayStarter on this but my company I ordered it to wiped the HD, including the HP_TOOLS partition. How can I reinstall it? It doesn't seem to be on the HP Support site or on the CD that came with
-
Hi all y at - it a way to color a Boolean control system. I use a Boolean system control with "changes when you press on" mechanical Action. He wants her to be green when it is real and by default if the value False. But I am unable to color in the c
-
while loop: delay enforcement and continuous updated: VI back to fake out of time?
Hi all I want to control the time of execution of a while loop. I want the user to have the ability to decide how long he wants to run the while loop. The while loop is used to update certain values, then it should run continuously, not only run once