Help to refine this query
Query function: list out all case no, paid amout that occured for LAST 2 fiscal years for each owner at any given time plus separte sum column for each FY
Question: I don't like my query with repetition ( what if we need last 10 years). Can you help me refine it ?
many thanks.
create table test_case_payment
case_no number not null,
owner_no number not null,
paid_amt number(13,2),
paid_date date
create table test_case_quota
case_no number not null,
limit number not null
insert into test_case_payment(case_no,owner_no,paid_amt,paid_date)
-- data represents FY 2011,2012,2012,2008,2010
values(1,810,2700,to_date('10/25/2010','MM/DD/YYYY'));
values(2,820,350,to_date('07/05/2011','MM/DD/YYYY'));
values(3,810,900,to_date('01/01/2011','MM/DD/YYYY'));
values(4,840,100,to_date('04/05/2008','MM/DD/YYYY'));
values(5,850,20,to_date('07/20/2009','MM/DD/YYYY'));
Insert into test_case_quota(case_no,limit)
-- paid ceiling
values(1,2);
values(2,2);
values(3,1);
values(4,1);
values(5,1);
-- query starts here
with FY1 as
select a.case_no,a.owner_no, a.paid_amt,b.limit,
NVL(sum(a.paid_amt) over (partition by a.owner_no),0) FY1_TOTAL
from test_case_payment a,test_case_quota b
where
a.case_no=b.case_no
and a.paid_date between to_date('7/1/'|| ( EXTRACT (YEAR FROM to_date(:FY_BEGIN,'MM/DD/YYYY')) ),'MM/DD/YYYY') and to_date('06/30/' || ( EXTRACT (YEAR FROM to_date(:FY_BEGIN,'MM/DD/YYYY'))+1),'MM/DD/YYYY')
order by a.owner_no,a.case_no
FY2 as
select a.case_no,a.owner_no, a.paid_amt,b.limit,
NVL(sum(a.paid_amt) over (partition by a.owner_no),0) FY2_TOTAL
from test_case_payment a,test_case_quota b
where
a.case_no=b.case_no
and a.paid_date between to_date('7/1/'|| ( EXTRACT (YEAR FROM to_date(:FY_BEGIN,'MM/DD/YYYY')) +1),'MM/DD/YYYY') and to_date('06/30/' || ( EXTRACT (YEAR FROM to_date(:FY_BEGIN,'MM/DD/YYYY'))+2),'MM/DD/YYYY')
order by a.owner_no,a.case_no
-- union 2 temp tables
FY_UNION as
(select case_no,owner_no,paid_amt,limit,
FY1_TOTAL Y1,null Y2 from FY1
union
select case_no,owner_no,paid_amt,limit,
null Y1,FY2_TOTAL Y2 from FY2)
-- main query
select case_no,owner_no,paid_amt,limit,Y1,Y2 from FY_UNION
order by owner_no
-- result
CASE_NO OWNER_NO PAID_AMT LIMIT Y1 Y2
1 810 2700 2 - 3600
3 810 900 1 - 3600
5 850 20 1 20 -Edited by: wanwan63 on Oct 30, 2011 11:03 AM
added format code to display bettter readable output
Yes, good idea to use a working schema as a proxy. Here's a variation that takes the department as owner and employee as the payment, and returns all payments with amount (=salary) sums for 3 years (I've skipped the FY stuff)...
WITH y AS
SELECT LEVEL AS year_num
, ADD_MONTHS ( TO_DATE ('01011998', 'DDMMYYYY')
, 12 * (LEVEL - 1)
) this_year_begin
, ADD_MONTHS ( TO_DATE ('01011998', 'DDMMYYYY')
, 12 * LEVEL
) next_year_begin
FROM dual
CONNECT BY LEVEL <= 3 -- Can be any positive integer
), t AS (
SELECT y.year_num, d.department_name, e.salary, e.hire_date,
Sum (CASE WHEN e.hire_date >= y.this_year_begin
AND e.hire_date < y.next_year_begin THEN e.salary END)
OVER (PARTITION BY d.department_name, y.year_num) sumsal
FROM employees e
JOIN departments d
ON d.department_id = e.department_id
CROSS JOIN y
WHERE e.hire_date >= TO_DATE ('01011998', 'DDMMYYYY')
SELECT department_name, hire_date, salary,
Sum (CASE year_num WHEN 1 THEN sumsal END) y1,
Sum (CASE year_num WHEN 2 THEN sumsal END) y2,
Sum (CASE year_num WHEN 3 THEN sumsal END) y3
FROM t
GROUP BY department_name, salary, hire_date
ORDER BY 1, 2;
DEPT HIRE_DATE SALARY Y1 Y2 Y3
Finance 07-MAR-98 7800 7800 6900
Finance 07-DEC-99 6900 7800 6900
IT 05-FEB-98 4800 4800 4200
IT 07-FEB-99 4200 4800 4200
Purchasing 15-NOV-98 2600 2600 2500
Purchasing 10-AUG-99 2500 2600 2500
Sales 24-JAN-98 9600 59100 42200 49400
Sales 23-MAR-98 10000 59100 42200 49400
Sales 24-MAR-98 8600 59100 42200 49400
Sales 30-MAR-98 8000 59100 42200 49400
Sales 23-APR-98 8400 59100 42200 49400
Sales 03-NOV-98 7000 59100 42200 49400
Sales 09-DEC-98 7500 59100 42200 49400
Sales 23-FEB-99 7400 59100 42200 49400
Sales 19-MAR-99 9500 59100 42200 49400
Sales 24-MAR-99 7300 59100 42200 49400
Sales 15-OCT-99 11000 59100 42200 49400
Sales 23-NOV-99 7000 59100 42200 49400
Sales 04-JAN-00 6200 59100 42200 49400
Sales 24-JAN-00 7200 59100 42200 49400
Sales 29-JAN-00 10500 59100 42200 49400
Sales 23-FEB-00 6800 59100 42200 49400
Sales 24-MAR-00 6400 59100 42200 49400
Sales 21-APR-00 6100 59100 42200 49400
Sales 21-APR-00 6200 59100 42200 49400
Shipping 24-JAN-98 3200 37800 26100 9800
Shipping 12-FEB-98 2700 37800 26100 9800
Shipping 23-FEB-98 3100 37800 26100 9800
Shipping 15-MAR-98 2600 37800 26100 9800
Shipping 06-APR-98 2500 37800 26100 9800
Shipping 24-APR-98 3100 37800 26100 9800
Shipping 23-MAY-98 3000 37800 26100 9800
Shipping 24-JUN-98 3400 37800 26100 9800
Shipping 01-JUL-98 3200 37800 26100 9800
Shipping 09-JUL-98 2500 37800 26100 9800
Shipping 11-JUL-98 2900 37800 26100 9800
Shipping 26-AUG-98 2900 37800 26100 9800
Shipping 28-SEP-98 2700 37800 26100 9800
Shipping 14-JAN-99 2400 37800 26100 9800
Shipping 07-FEB-99 3000 37800 26100 9800
Shipping 17-MAR-99 2800 37800 26100 9800
Shipping 10-APR-99 2100 37800 26100 9800
Shipping 21-JUN-99 2500 37800 26100 9800
Shipping 21-JUN-99 2600 37800 26100 9800
Shipping 16-NOV-99 5800 37800 26100 9800
Shipping 12-DEC-99 2400 37800 26100 9800
Shipping 19-DEC-99 2500 37800 26100 9800
Shipping 13-JAN-00 2600 37800 26100 9800
Shipping 03-FEB-00 2800 37800 26100 9800
Shipping 06-FEB-00 2200 37800 26100 9800
Shipping 08-MAR-00 2200 37800 26100 9800
51 rows selected.
Start edit:
This is actually quite an interesting problem, where neither group by nor analytics alone can solve the problem, so I'll explain how my solution works. I did find a simpler solution though when thinking the explanation through that requires just a small addition to anaytics.
Grouping won't work because it removes the transaction detail, but the obvious partitioning, department and year, won't work either because then the summation would only be for the transaction's own year. That is why I cross-joined Frank's years view, so that now each transaction is joined to each of the years, and we can then partition by the view year. The first CASE is necessary to sum only the relevant year's transactions for each year row, which we then pivot into columns in the standard way.
The simpler solution involves partitioning by department only, then using a CASE within the summation to sum the relevant year for each column. [Edited to replace hard-coded dates with input and offsets]. I won't repeat the output, I have tested that it's the same as above.
VARIABLE fy_begin NUMBER
EXEC :fy_begin := 1998;
SELECT d.department_name dept, e.hire_date, e.salary,
Sum (CASE WHEN To_Number (To_Char(e.hire_date, 'YYYY')) = :fy_begin THEN e.salary END)
OVER (PARTITION BY d.department_name) y1,
Sum (CASE WHEN To_Number (To_Char(e.hire_date, 'YYYY')) = :fy_begin+1 THEN e.salary END)
OVER (PARTITION BY d.department_name) y2,
Sum (CASE WHEN To_Number (To_Char(e.hire_date, 'YYYY')) = :fy_begin+2 THEN e.salary END)
OVER (PARTITION BY d.department_name) y3
FROM employees e
JOIN departments d
ON d.department_id = e.department_id
WHERE e.hire_date >= To_Date ('0101' || To_Char (:fy_begin), 'DDMMYYYY')
ORDER BY 1, 2;I hope it's clear that the solutions do translate directly to the OP's problem. You can add the FY stuff in either by Frank's view or just replacing the To_Numbered bit by a CASE based on month number being 1-6 or not and the year - it's a bit simpler using CY.
Edited by: BrendanP on 30-Oct-2011 01:20
Edited by: BrendanP on 30-Oct-2011 02:01
Similar Messages
-
Can u help me refine this query
create table company
(comp_id number primary key,
comp_name varchar2(50) not null
create table accident
(acc_seq number primary key,
acc_comp_id number not null,
acc_series smallint not null,
acc_id varchar2(10) not null,
acc_type varchar2(50) not null)
-- acc_series is an auto number to tell me total accident this company has so far
insert into company(comp_id,comp_name)
values(10001,'A Corp')
insert into company(comp_id,comp_name)
values(10002,'B Corp')
insert into company(comp_id,comp_name)
values(10003,'C Corp')
insert into accident(acc_seq,acc_comp_id,acc_series,acc_id,acc_type)
values(9001,10001,1,'AC-09-0001','CAR')
insert into accident(acc_seq,acc_comp_id,acc_series,acc_id,acc_type)
values(9002,10002,1,'AC-09-0002','MACHINARY')
insert into accident(acc_seq,acc_comp_id,acc_series,acc_id,acc_type)
values(9003,10001,2,'AC-09-0009','FIELD')
-- problem for this query : I hardcoded number 1,2. In reality, I need a way to find the upper bound first then do the decode ( I think) and adjust the column heading accordingly, can u help ?
select
comp_name,
max(decode(acc_series,1,acc_id)) acc1_id,
max(decode(acc_series,1,acc_type)) acc1_type,
max(decode(acc_series,2,acc_id)) acc2_id,
max(decode(acc_series,2,acc_type)) acc2_type
from company A,accident B
where A.comp_id=B.acc_comp_id
group by comp_name
output
COMP_NAME ACC1_ID ACC1_TYPE ACC2_ID ACC2_TYPE
A Corp AC-09-0001 CAR AC-09-0009 FIELD
B Corp AC-09-0002 MACHINARY
Thanks in advance.
MunsharIt looks like you are after a dynamic pivot.
Check out this post by Frank that goes through an example on how to create a dynamic pivot: {message:id=3227388} -
Need help in refining the query
Hello Experts,
Need your help in refining the query further more.
table structure
Mskey Col A Col B
1 empno [20141127-20151128]1234
1 empno [20151201-99991231]232544
1 salutation [20141127-99991231]Mrs
1 salutation [20151127-99991231]Mr
2 empno [20141127-20151128]1234
2 empno [20151201-99991231]232544
2 salutation [20141127-99991231]Mrs
2 salutation [20151127-99991231]Mr
My requirement is to find the list of overlapping records based on the dates
user details may be varying from time to time as new data would be pushed through HR systems to identity store via an interface.
The job is getting failed whenever there is any overlapping with dates. So we proactively decided to schedule a job in this regards which runs weekly and would let us know for which and all the users there is overlapping dates are there, so that we can send the list to HR team for pushing new data.
Overlapping Issue Example:
The users employee id for an year it is 1234 and later he moved to another department and his employee id got changed and it became 2345 remaining all details are same. So the HR systems send the data for this user as empno - [20141127-20151128]1234 and empno - [20151201-99991231]232544
it means from 20141127 to 20151128 his employee no is 1234 and from 20151201 to 99991231 his employee would be 2345.
This is a correct case and the tool would accept this data.
the below cases are invald
Case 1: 1 salutation [20141127-99991231]Mrs 1 salutation [20151127-99991231]Mr
Case 2: 2 salutation [20141127-99991231]Mrs 2 salutation [20141127-99991231]Mr
So we wanted to find these overlapping records from tables.
My Query:
I am able to successfully write query for the case 2 type but unable to write for case1.
select id,colA
count(left(ColB,CHARINDEX(']',ColB))) as 'Count'
from tblA with (nolock)
where id in (Select distinct id from tblb with (nolock))
group by id, cola,left(ColB,CHARINDEX(']',ColB))
having count(left(ColB,CHARINDEX(']',ColB)))>1Finally got the required answer with the below query
WITH Cte AS
SELECT ID,ColA,ColB,ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS RN,
CAST(SUBSTRING(ColB,2,CHARINDEX('-',ColB)-2) AS DATE) AS StartDT,
CAST(SUBSTRING(ColB,CHARINDEX('-',ColB)+1,8) AS DATE) AS EndDT FROM TblA
SELECT c1.ID, c1.ColA,c1.ColB
FROM Cte c1 JOIN Cte c2
ON c1.RN != c2.RN
AND c1.ID=c2.ID
AND c1.ColA=c2.ColA
AND (c1.StartDT BETWEEN c2.StartDT AND c2.EndDT OR c2.StartDT BETWEEN c1.StartDT AND c1.EndDT ) -
Hi,
I'm using below query in procedure.It's taking more more time can some one help to tune this query or advice to rewrite the query.
Databse :10.1
SELECT 'Reading Comprehension' TEST_NAME,T.TEST_END_DATE TEST_SESSION_DATE,
C.POOL_VERSION_ID, I.CREATED_ON POOL_CREATED_DT,
C.ITEM_ID, C.ITEM_RESPONSE_ID, S.STUDENT_ID_PK, C.RESPONSE_KEY, C.IS_CORRECT RESPONSE_IS_CORRECT,
T.SCORE SCALE_SCORE, C.RESPONSE_DURATION, P.ITEM_KEY,
T.TEST_SESSION_DETAIL_ID, SYSDATE CREATED_ON
-- BULK COLLECT INTO TV_PSYCHO_DET
FROM
CAT_ITEM_PARAMETER P, CAT_ITEM_USER_RESPONSE C, TEST_SESSION_DETAIL T,
TEST_SESSION S, ITEM_POOL_VERSION I, TEST_DETAIL D
,INSTITUTION E
WHERE TRUNC(T.TEST_END_DATE) BETWEEN TO_DATE('01-11-09','dd-mm-yy') AND TO_DATE('30-11-09','dd-mm-yy')
AND D.TEST_NAME = 'Reading Comprehension'
AND T.TEST_SESSION_STATUS_ID = 3
AND I.POOL_AVAILABILITY='Y'
AND P.PRETEST=0 AND C.RESTART_FLAG=0
AND T.TEST_DETAIL_ID = D.TEST_DETAIL_ID
AND S.TEST_SESSION_ID = T.TEST_SESSION_ID
AND C.TEST_SESSION_DETAIL_ID = T.TEST_SESSION_DETAIL_ID
AND S.INSTITUTION_ID=E.INSTITUTION_ID
AND SUBSTR(E.INSTITUTION_ID_DISPLAY,8,3) <> '000'
AND I.ITEM_ID = C.ITEM_ID
AND P.ITEM_ID = I.ITEM_ID;expln plan
Plan hash value: 3712814491
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time | Pstart|
Pstop |
| 0 | SELECT STATEMENT | | 50857 | 7151K| 93382 (1)| 00:18:41 | |
|
|* 1 | FILTER | | | | | | |
|
|* 2 | HASH JOIN | | 50857 | 7151K| 93382 (1)| 00:18:41 | |
|
| 3 | PARTITION HASH ALL | | 2312 | 23120 | 25 (0)| 00:00:01 | 1 |
5 |
|* 4 | TABLE ACCESS FULL | CAT_ITEM_PARAMETER | 2312 | 23120 | 25 (0)| 00:00:01 | 1 |
5 |
|* 5 | HASH JOIN | | 94938 | 12M| 93356 (1)| 00:18:41 | |
|
|* 6 | TABLE ACCESS FULL | ITEM_POOL_VERSION | 9036 | 132K| 30 (0)| 00:00:01 | |
|
|* 7 | TABLE ACCESS BY GLOBAL INDEX ROWID | CAT_ITEM_USER_RESPONSE | 9 | 279 | 18 (0)| 00:00:01 | ROWID |
ROWID |
| 8 | NESTED LOOPS | | 45349 | 5270K| 93325 (1)| 00:18:40 | |
|
|* 9 | HASH JOIN | | 4923 | 423K| 11377 (1)| 00:02:17 | |
|
|* 10 | INDEX FAST FULL SCAN | INSTI_ID_NAME_COUN_DISP_IDX | 8165 | 111K| 18 (0)| 00:00:01 | |
|
|* 11 | HASH JOIN | | 4923 | 355K| 11359 (1)| 00:02:17 | |
|
|* 12 | TABLE ACCESS BY GLOBAL INDEX ROWID| TEST_SESSION_DETAIL | 4107 | 148K| 6804 (1)| 00:01:22 | ROWID |
ROWID |
| 13 | NESTED LOOPS | | 4923 | 278K| 6806 (1)| 00:01:22 | |
|
|* 14 | INDEX RANGE SCAN | TEST_DETAIL_AK_1 | 1 | 21 | 2 (0)| 00:00:01 | |
|
|* 15 | INDEX RANGE SCAN | TEST_SESSION_DETAIL_FK2_I | 39737 | | 102 (0)| 00:00:02 | |
|
| 16 | PARTITION HASH ALL | | 1672K| 25M| 4546 (1)| 00:00:55 | 1 |
5 |
| 17 | TABLE ACCESS FULL | TEST_SESSION | 1672K| 25M| 4546 (1)| 00:00:55 | 1 |
5 |
|* 18 | INDEX RANGE SCAN | CAT_ITEM_USER_RESP_IDX1 | 18 | | 3 (0)| 00:00:01 | |
|
Predicate Information (identified by operation id):
1 - filter(TO_DATE('01-11-09','dd-mm-yy')<=TO_DATE('30-11-09','dd-mm-yy'))
2 - access("P"."ITEM_ID"="I"."ITEM_ID")
4 - filter("P"."PRETEST"=0)
5 - access("I"."ITEM_ID"="C"."ITEM_ID")
6 - filter("I"."POOL_AVAILABILITY"='Y')
7 - filter(TO_NUMBER("C"."RESTART_FLAG")=0)
9 - access("S"."INSTITUTION_ID"="E"."INSTITUTION_ID")
10 - filter(SUBSTR("E"."INSTITUTION_ID_DISPLAY",8,3)<>'000')
11 - access("S"."TEST_SESSION_ID"="T"."TEST_SESSION_ID")
12 - filter(TRUNC(INTERNAL_FUNCTION("T"."TEST_END_DATE"))>=TO_DATE('01-11-09','dd-mm-yy') AND "T"."TEST_SESSION_STATUS_ID"=3
AND TRUNC(INTERNAL_FUNCTION("T"."TEST_END_DATE"))<=TO_DATE('30-11-09','dd-mm-yy'))
14 - access("D"."TEST_NAME"='Reading Comprehension')
15 - access("T"."TEST_DETAIL_ID"="D"."TEST_DETAIL_ID")
18 - access("C"."TEST_SESSION_DETAIL_ID"="T"."TEST_SESSION_DETAIL_ID")
43 rows selected.Edited by: user575115 on Dec 18, 2009 12:31 AMWhen you see something like ...
7 - filter(TO_NUMBER("C"."RESTART_FLAG")=0) It means that Oracle had to do a conversion for you since you aren't using the proper data type in your query.
That would mean IF there is an index on that column, it won't be useable... -
i am using
Oracle8i Enterprise Edition Release 8.1.7.4.0 - Production
With the Partitioning option
JServer Release 8.1.7.4.0 - Production
Please help to simplify this query. I also want to make this as a procedure.
select
RH.resort as RH_RESORT,
RH.rate_code as RH_RATE_CODE,
RD.rate_detail_id as RD_RATE_DETAIL_ID,
RD.rate1 as RD_RATE1,
RD.rate2 as RD_RATE2,
RD.rate3 as RD_RATE3,
RD.rate4 as RD_RATE4,
RD.rate5 as RD_RATE5,
RRC.room_category as RM_CAT,
initcap(RRMCAT.long_description) as RM_DESC,
RH.DAY1,
RH.DAY2,
RH.DAY3,
RH.DAY4,
RH.DAY5,
RH.DAY6,
RH.DAY7,
RH.WEEKEND1,
RH.WEEKEND2,
RH.WEEKEND3,
RH.WEEKEND4,
RH.WEEKEND5,
RH.WEEKEND6,
RH.WEEKEND7
from pms_rate_header RH,
pms_rate_detail RD,
pms_rate_room_cat RRC,
resort_room_category RRMCAT
where RH.inactive_date is NULL
and RH.RESORT='FABGOI'
and RH.RATE_CODE ='CRRRACK'
and ('15-Jan-2007' >= RH.BEGIN_DATE
and '16-Jan-2007' <= RH.END_DATE)
and RD.rate_header_id=RH.rate_header_id
and RD.inactive_date is NULL
and ('15-Jan-2007' >= RD.BEGIN_DATE
and '16-Jan-2007' <= RD.END_DATE)
and RRC.rate_detail_id=RD.rate_detail_id
and RRC.resort=RH.resort
and RRMCAT.resort=RH.resort
and RRMCAT.room_category=RRC.room_category
and RRC.inactive_date is NULL
and RRMCAT.inactive_date IS NULL
regards
lee1212where RH.inactive_date is NULL
and RH.RESORT='FABGOI'
and RH.RATE_CODE ='CRRRACK'
and ('15-Jan-2007' >= RH.BEGIN_DATE
and '16-Jan-2007' <= RH.END_DATE)
and RD.rate_header_id=RH.rate_header_id
and RD.inactive_date is NULL
and ('15-Jan-2007' >= RD.BEGIN_DATE
and '16-Jan-2007' <= RD.END_DATE)
and RRC.rate_detail_id=RD.rate_detail_id
and RRC.resort=RH.resort
and RRMCAT.resort=RH.resort
and RRMCAT.room_category=RRC.room_category
and RRC.inactive_date is NULL
and RRMCAT.inactive_date IS NULL
in the above part i am finding repeated joins and lot of 'and's
i want to know any line can be eliminated or the the query can be rewritten in a simple way without affecting it's accuracy?
regards
Lee1212 -
Hi,
Can you’ll please help me with this query.
Here is a little bit of background:
One title can have multiple items associated with it.
Table: TITLE has the master list of titles. TITLE_ID is the primary key.
Table: ITEM has the master list of all items. ITEM_ID is the primary. This table also has the TITLE_ID which stores title for this item.
Table: ITEM_STATUS has fields ITEM_ID and STATUS_ID. This field contains statuses for items. But not all items contained in the table ITEM are in this table.
I want to find TITLE_ID’s whose all items (all ITEM_ID in table ITEM having same value for TITLE_ID) have a particular status (for example STATUS_ID = 2) in table ITEM_STATUS.
Let’s say TITLE_ID = 1 has 5 items in table ITEM_ID and only 4 items out of it in table ITEM_STATUS with STATUS_ID = 2, then this TITLE_ID should not come. OR
Let’s say TITLE_ID = 1 has 5 items in table ITEM_ID and all these 5 items are in table ITEM_STATUS but only 1 has STATUS_ID = 2, then this TITLE_ID should also not come
In the above case only if all 5 items are contained in table ITEM_STATUS have STATUS_ID = 2 then this TITLE_ID should be reported by the query.
What should be the query like for this one, I am fairly new to SQL so plz guide me.
Thank you,
RajaI haven't tested the query below. Try it and let me know for any issues:
SELECT DISTINCT t.title_id
FROM title t,
item i,
item_status its
WHERE t.title_id = i.title_id
AND i.item_id = its.item_id
AND NOT EXISTS (
SELECT 1
FROM item_status its1
WHERE its1.item_id = i.item_id
AND status_id <> 'YOUR_ITEM_STATUS'
) -
Please help to modifiy this query for better performance
Please help to rewrite this query for better performance. This is taking long time to execute.
Table t_t_bil_bil_cycle_change contains 1200000 rows and table t_acctnumberTab countains 200000 rows.
I have created index on ACCOUNT_ID
Query is shown below
update rbabu.t_t_bil_bil_cycle_change a
set account_number =
( select distinct b.account_number
from rbabu.t_acctnumberTab b
where a.account_id = b.account_id
Table structure is shown below
SQL> DESC t_acctnumberTab;
Name Type Nullable Default Comments
ACCOUNT_ID NUMBER(10)
ACCOUNT_NUMBER VARCHAR2(24)
SQL> DESC t_t_bil_bil_cycle_change;
Name Type Nullable Default Comments
ACCOUNT_ID NUMBER(10)
ACCOUNT_NUMBER VARCHAR2(24) YIshan's solution is good. I would avoid updating rows which already have the right value - it's a waste of time.
You should have a UNIQUE or PRIMARY KEY constraint on t_acctnumberTab.account_id
merge rbabu.t_t_bil_bil_cycle_change a
using
( select distinct account_number, account_id
from rbabu.t_acctnumberTab
) t
on ( a.account_id = b.account_id
and decode(a.account_number, b.account_number, 0, 1) = 1
when matched then
update set a.account_number = b.account_number -
Could you please help me make this query less complicated
could you please help me make this query less complicated
select t1.R_OBJECT_ID
from dm_relation_sp a, ddt_resolution_sp t1
where a.parent_id = '0900000283560456' -----------ID
and a.child_id = t1.R_OBJECT_ID
union all
select t3.R_OBJECT_ID
from ddt_resolution_sp t3
where t3.R_OBJECT_ID in (select t2.child_id
from dm_relation_sp t2
where t2.parent_id in (select a.child_id
from asud_fsk.dm_relation_sp a, asud_fsk.ddt_resolution_sp t1
where a.parent_id = '0900000283560456' -----------ID
and a.child_id = t1.R_OBJECT_ID))
union all
select t4.R_OBJECT_ID
from ddt_resolution_sp t4
where t4.R_OBJECT_ID in(
select t3.child_id from dm_relation_sp t3
where t3.parent_id in (
select t2.child_id
from asud_fsk.dm_relation_sp t2
where t2.parent_id in (select a.child_id
from asud_fsk.dm_relation_sp a, asud_fsk.ddt_resolution_sp t1
where a.parent_id = '0900000283560456' -----------ID
and a.child_id = t1.R_OBJECT_ID))
and t3.relation_name = 'RESOLUTION_RELATION')
union all
select t5.R_OBJECT_ID
from ddt_resolution_sp t5
where t5.R_OBJECT_ID in
(select t4.child_id
from dm_relation_sp t4
where t4.parent_id in(
select t3.child_id from dm_relation_sp t3
where t3.parent_id in (
select t2.child_id
from asud_fsk.dm_relation_sp t2
where t2.parent_id in (select a.child_id
from asud_fsk.dm_relation_sp a, asud_fsk.ddt_resolution_sp t1
where a.parent_id = '0900000283560456' -----------ID
and a.child_id = t1.R_OBJECT_ID))
and t3.relation_name = 'RESOLUTION_RELATION')
and t4.relation_name = 'RESOLUTION_RELATION')
Edited by: user13025450 on 29.04.2010 16:23Hi,
Welcome to the forum! You'll find that there are many qualified people (such as Tubby) willing to help you. Will you do what you can to help them? In order to simplify the query you posted,someone will first have to understand what it does, what the tables that it uses are like, and what tools you have to work with (that is, what version of Oracle, and any other software you are using). To actually test their ideas, people will need versions of your tables.
Many people, if they spent enough time, might be able to figure out roughly what you are doing, make some tables themselves and test a solution. You can help with all of that. I assume you already know what the appliction is, and what this particular query is supposed to do: you don't have to figure out any of that, you just have to say it. You know what all your tables are, what the datatypes of all the columns are, and what kinds of data are in the tables: you don't have to guess at any of that.
Describe what you're doing. Think about it: how do we know that
SELECT NULL
FROM dual;doesn't do what you want?
Post CREATE TABLE and INSERT statements for a little sample data.
Post the results that this query is supposed to produce from those results. (Is it producing the right output now? Then it should be easy to post the correct results.)
Describe, as well as you can, how the present query is doing it.
Format your existing code, so it's easy to see what the different branches of the UNION are, and what the main clauses are in each one.
When posting formatted text (code or results) type these 6 characters
\(all small letters, inside curly brackets) before and after each formatted section, to keep this site from compressing the spaces.
Say what versions of Oracle (e.g. 10.2.0.3.0) and any other relevant software you are using.
I know it's a lot of work, but it really helps. You can do it as well (probably better) than anyone else, and if you're unwilling to do it, why should anyone else be willing? -
I would like to create a view on this table with four columns
1. PN#_EXP_DATE
2. PN#
3. PN#_EFF_DATE
4. PN#
P_S_C A_C P EXP_DT
21698 13921 1 5/29/2009 3:15:41 PM
21698 13921 1 5/29/2009 3:54:57 PM
21698 1716656 4 5/29/2009 3:15:41 PM
21698 3217 3 5/29/2009 3:15:40 PM
21698 3217 3 5/29/2009 3:54:57 PM
21698 60559 2 5/29/2009 3:15:41 PM
21698 60559 2 5/29/2009 3:54:57 PM
I have a trigger on A, which inserts the DML records into B. (Table A and B structure is the almost the same,
where table B will have one extra column exp_dt)
NOw Table B can have records with same P_S_C and A_C columns and exp_dt will capture the history.
for example: from the above sample data, let us take first two records..
P_S_C A_C P EXP_DT
21698 13921 1 5/29/2009 3:15:41 PM --- Record 1
21698 13921 1 5/29/2009 3:54:57 PM --- Record 2
from this..
Note: 1. Table A and Table C can be joined using A.P_S_C and C.R_C to get the start_date.
2. PN# comes from table D. It contains numbers for the resp. weeks.
3. PN#_EFF_DATE is the previous immediate previous date for that record in history table (Table B).
I wanted the data like..
---- this is for the second record in the above..
PN#_EXP_DATE PN# PN#_EFF_DATE PN#
5/29/2009 3:54:57 PM 214 5/29/2009 3:15:41 PM 214
---- this is for the first record in the above..
PN#_EXP_DATE PN# PN#_EFF_DATE PN#
5/29/2009 3:54:41 PM 214 ( for this we should query the table C to get the
start_date, for this combinatation of P_S_C and A_C in table B
where B.P_S_C = C.A_C
and that value should be the EFF_DT for this record)
Please help me with this....
Thanks in advance..Hi All,
select d.P# as "PN#_EXP_DATE", exp_date
from daily_prd d, cbs1_assoc_hist b
where to_char(d.day_date,'MM/DD/YYYY') = to_char(b.exp_date,'MM/DD/YYYY')
and d.period_type = 'TIMEREPORT';
This above query gives the output as follows:
pn#_exp_date exp_date
214 5/29/2009 3:15:40 PM
214 5/29/2009 3:15:41 PM
214 5/29/2009 3:15:41 PM
214 5/29/2009 3:15:41 PM
214 5/29/2009 3:54:57 PM
214 5/29/2009 3:54:57 PM
214 5/29/2009 3:54:57 PM
This below is the data from history table (Table B).
P_S_C A_C PLACE EXP_DATE
21698 3217 3 5/29/2009 3:15:40 PM
21698 13921 1 5/29/2009 3:15:41 PM
21698 1716656 4 5/29/2009 3:15:41 PM
21698 60559 2 5/29/2009 3:15:41 PM
21698 13921 1 5/29/2009 3:54:57 PM
21698 3217 3 5/29/2009 3:54:57 PM
21698 60559 2 5/29/2009 3:54:57 PM
I got the pn#_exp_date from the Table 'D', for the given exp_date from Table B.
My question is again....
CASE - 1
from the given records above, I need to look for exp_date for the given same P_S_C and A_C.
in this case we can take the example...
P_S_C A_C PLACE EXP_DATE
21698 3217 3 5/29/2009 3:15:40 PM
21698 3217 3 5/29/2009 3:54:57 PM
In this case, the
pn#_exp_date exp_date pn#_eff_date eff_date
214 5/29/2009 3:15:57 PM < PN# corresponding to the 5/29/2009 3:15:40 PM
eff_date .>
<Basically the eff_date is
nothing but the exp_date only.
we should take the immediate before one.
In this case, our eff_date is '5/29/2009 3:15:40 PM'.
but how to get this.
CASE - 2
from the above sample data, consider this
P_S_C A_C PLACE EXP_DATE
21698 1716656 4 5/29/2009 3:15:41 PM
In this case, there is only one record for the P_S_C and A_C combination.
The expected result :
pn#_exp_date exp_date pn#_eff_date eff_date
214 5/29/2009 3:15:41 PM < PN# corresponding to the 5/29/2009 3:15:40 PM
eff_date .>
<Basically the eff_date is
nothing but the exp_date only.
we should take the immediate before one.
In this case to get the eff_date, we should query the Table 'C', to get the eff_date, which is START_DT column in this table.
for this join B.P_S_C and C.R_C.
Hope I am clear now..
Thanks in advance..... -
Hi,
I have a query in my proj where the same table is looked up twice in the same query.
Can anybody suggest in improving the performance of this query?
select * from table1 a1 where (a1.column1, a1.column2, a1.column3, a1.column4, a1.column5, a1.column6, a1.column7, a1.column8, a1.column9,
a1.column10) in ( select a2.column1, a2.column2, a2.column3, a2.column4, a2.column5, a2.column6, a2.column7, a2.column8, a2.column9,
a2.column10 from table1 a2 where column20 = '<condn>')
The table1 used here is same in outer query as well as the sub query. this is a example of what we use here, and the table1 contains 30 million rows. Though, creating index with 10 columns can be a option, we already have a unique index with 11 columns(which includes 10 from this query) and will that be helpful in anyway? or the same existing index can be forced?
Thanks a lot for ur timeDepending on the selectivity of column20 I am not sure Index is the best way to go. It might perform better with two full scans and a hash-join.
Anyway, I do prefer the syntax:
select /*+ leading(a2) */ a1.*
from table1 a1, table1 a2
where a2.column20 = '<condn>'
and a1.column1 = a2.column1
and a1.column2 = a2.column2
and a1.column3 = a2.column3
and a1.column4 = a2.column4
and a1.column5 = a2.column5
and a1.column6 = a2.column6
and a1.column7 = a2.column7
and a1.column8 = a2.column8
and a1.column9 = a2.column9
and a1.column10 = a2.column10;I've added a leading hint to tell oracle that the start table is a2. Might be useless.
Ensure your stats are up to date. You might need histograms here if your column20 is skewed.
Hope this helps,
François
Edited by: Francois Berger on Oct 24, 2008 1:47 AM -
Hi all i have this query:
SELECT VTA.CO_VENDEDOR
,VTA.NB_VENDEDOR
,VTA.CO_CLASE_CLIENTE
,VTA.DE_CLASE_CLIENTE
,VTA.CO_CLIENTE
,VTA.NB_CLIENTE
,VTA.MN_VENDIDO
,NVL(DEV.MN_DEVUELTO,0) MN_DEVUELTO
,VTA.MN_VENDIDO - NVL(DEV.MN_DEVUELTO,0) MN_NETO_VENDIDO
,NVL(COB.MN_COBRADO,0) MN_COBRADO
,NVL(COB.MN_DESCUENTO,0) MN_DESCUENTO
,NVL(COB.MN_COBRADO,0) + NVL(COB.MN_DESCUENTO,0) MN_COBRADO_MAS_DESCUENTO
FROM (SELECT FCL.CTV_CO_CLASE_ORGANIZACION CO_CLASE_CLIENTE
,FCL.CTV_DE_CLASE_ORGANIZACION DE_CLASE_CLIENTE
,FCL.CO_ORGANIZACION CO_CLIENTE
,FCL.ORG_NB_CLIENTE NB_CLIENTE
,FCL.PER_CO_IDENTIFICACION_VENDEDOR CO_VENDEDOR
,FCL.PER_NB_PRIMER_NOMBRE_VENDEDOR||' '||
FCL.PER_NB_PRIMER_APELLIDO_VEND NB_VENDEDOR
,SUM((CA_PRODUCTO * (PR_PRODUCTO - NVL(PR_DESCUENTO_PRODUCTO,0))) * (1 - NVL(PC_DESCUENTO,0))) MN_VENDIDO
FROM S04_FACTURA_CLIENTE_TOTAL_R FCL
,S04_FACTURA_CLIENTE_PRD_TOT FPR
,(SELECT FCP.FAC_ID_FACTURA
,SUM(DDC.MN_DEBITO_CREDITO) /
SUM(FCP.CA_PRODUCTO * (FCP.PR_PRODUCTO - NVL(FCP.PR_DESCUENTO_PRODUCTO,0))) PC_DESCUENTO
FROM S04_DOCUMENTO_DEBITO_CREDITO_R DDC
,S04_FACTURA_CLIENTE_PRD_TOT FCP
WHERE DDC.ID_DOCUMENTO_REFERENCIA = FCP.FAC_ID_FACTURA
AND DDC.TDC_IN_DEBITO_CREDITO = 'C'
GROUP BY FCP.FAC_ID_FACTURA) DCT
WHERE FCL.ID_REGISTRO = FPR.FAC_ID_FACTURA
AND DCT.FAC_ID_FACTURA (+) = FPR.FAC_ID_FACTURA
AND FCL.FE_EMISION BETWEEN to_date('01112009','ddmmyyyy') AND to_date('29112009','ddmmyyyy')
AND FCL.ORG_ID_CLIENTE = NVL(NULL,FCL.ORG_ID_CLIENTE)
AND FCL.PER_ID_VENDEDOR = NVL(7647771,FCL.PER_ID_VENDEDOR)
AND FCL.CTV_CO_ESTADO_DOCUMENTO = 'EM'
AND FCL.UBG_ID_UBICACION_CLIENTE in (SELECT ID_REGISTRO
FROM S00_UBICACION_GEOGRAFICA
START WITH ID_REGISTRO = nvl(NULL, FCL.UBG_ID_UBICACION_CLIENTE)
CONNECT BY PRIOR ID_REGISTRO = UBG_ID_UBICACION_PADRE)
GROUP BY FCL.CTV_CO_CLASE_ORGANIZACION
,FCL.CTV_DE_CLASE_ORGANIZACION
,FCL.CO_ORGANIZACION
,FCL.ORG_NB_CLIENTE
,PER_CO_IDENTIFICACION_VENDEDOR
,PER_NB_PRIMER_NOMBRE_VENDEDOR||' '||
PER_NB_PRIMER_APELLIDO_VEND) VTA
,(SELECT NDC .CTV_CO_CLASE_ORGANIZACION CO_CLASE_CLIENTE
,NDC.CTV_DE_CLASE_ORGANIZACION DE_CLASE_CLIENTE
,NDC.CO_CLIENTE
,NDC.ORG_NB_CLIENTE NB_CLIENTE
,FCL.PER_CO_IDENTIFICACION_VENDEDOR CO_VENDEDOR
,FCL.PER_NB_PRIMER_NOMBRE_VENDEDOR||' '||
FCL.PER_NB_PRIMER_APELLIDO_VEND NB_VENDEDOR
,SUM(CA_PRODUCTO * (PR_PRODUCTO - NVL(PR_DESCUENTO_PRODUCTO,0))) MN_DEVUELTO
FROM S06_NOTA_DEBITO_CREDITO_TOT_R NDC
,S06_DETALLE_NOTA_DEB_CRED_TOT DND
,S04_FACTURA_CLIENTE_TOTAL_R FCL
WHERE NDC.ID_REGISTRO = DND.NDC_ID_NOTA_DEBITO_CREDITO
AND NDC.CTV_CO_TIPO_DOCUMENTO = SK00_BUSCAR.F_VCT('CO_TIPO_DOCUMENTO_NOTA_CREDITO_FISCAL')
AND NDC.CTV_CO_ESTADO_DOCUMENTO = SK00_BUSCAR.F_VCT('CO_ESTADO_DOCUMENTO_EMITIDO')
AND NDC.FE_EMISION BETWEEN to_date('01112009','ddmmyyyy') AND to_date('29112009','ddmmyyyy')
AND (NDC.CTV_CO_MOTIVO_NOTA = SK00_BUSCAR.F_VCT('CO_MOTIVO_NOE_DEVOLUCION')
OR NDC.CTV_CO_MOTIVO_NOTA = SK00_BUSCAR.F_VCT('CO_MOTIVO_AJUSTE_PRECIO_NCD'))
AND NDC.ORG_ID_CLIENTE = NVL(NULL,NDC.ORG_ID_CLIENTE)
AND FCL.ID_REGISTRO = NDC.FAC_ID_FACTURA
AND FCL.CTV_CO_ESTADO_DOCUMENTO = 'EM'
AND FCL.UBG_ID_UBICACION_CLIENTE in (SELECT ID_REGISTRO
FROM S00_UBICACION_GEOGRAFICA
START WITH ID_REGISTRO = nvl(NULL, FCL.UBG_ID_UBICACION_CLIENTE)
CONNECT BY PRIOR ID_REGISTRO = UBG_ID_UBICACION_PADRE)
GROUP BY NDC.CTV_CO_CLASE_ORGANIZACION
,NDC.CTV_DE_CLASE_ORGANIZACION
,NDC.CO_CLIENTE
,NDC.ORG_NB_CLIENTE
,FCL.PER_CO_IDENTIFICACION_VENDEDOR
,FCL.PER_NB_PRIMER_NOMBRE_VENDEDOR||' '||
FCL.PER_NB_PRIMER_APELLIDO_VEND) DEV
,(SELECT RCD .CTV_CO_CLASE_ORGANIZACION CO_CLASE_CLIENTE
,RCD.CTV_DE_CLASE_ORGANIZACION DE_CLASE_CLIENTE
,RCD.CO_ORGANIZACION CO_CLIENTE
,RCD.ORG_NB_DISTRIBUIDOR NB_CLIENTE
,FCL.PER_CO_IDENTIFICACION_VENDEDOR CO_VENDEDOR
,FCL.PER_NB_PRIMER_NOMBRE_VENDEDOR||' '||
FCL.PER_NB_PRIMER_APELLIDO_VEND NB_VENDEDOR
,SUM(RCD.MN_DESCUENTO) MN_DESCUENTO
,SUM(DECODE(SIGN(RCO.MN_COBRADO_ANTES - IVA.MN_IVA)
,-1
,RCD.MN_ABONO - ABS(RCO.MN_COBRADO_ANTES - IVA.MN_IVA)
,RCD.MN_ABONO)) MN_COBRADO
FROM S06_RECIBO_COBRO_DOC_TOTAL_R RCD
,S04_FACTURA_CLIENTE_TOTAL_R FCL
,(SELECT ID_DOCUMENTO_REFERENCIA FAC_ID_FACTURA
,NVL(SUM(MN_DEBITO_CREDITO),0) MN_IVA
FROM S04_DOCUMENTO_DEBITO_CREDITO_R
WHERE TDC_CO_TIPO_DEBITO_CREDITO = SK00_BUSCAR.F_VCT('CO_TIPO_DEBITO_IVA')
GROUP BY ID_DOCUMENTO_REFERENCIA) IVA
,(SELECT ID_REFERENCIA FAC_ID_FACTURA
,NVL(SUM(MN_ABONO),0) MN_COBRADO_ANTES
FROM S06_RECIBO_COBRO_DOC_TOTAL_R
WHERE FE_EMISION < to_date('01112009','ddmmyyyy')
GROUP BY ID_REFERENCIA) RCO
WHERE RCD.CTV_CO_ESTADO_DOCUMENTO = SK00_BUSCAR.F_VCT('CO_ESTADO_DOCUMENTO_EMITIDO')
AND RCD.FE_EMISION BETWEEN to_date('01112009','ddmmyyyy') AND to_date('29112009','ddmmyyyy')
AND RCD.ORG_ID_ORGANIZACION = NVL(NULL,RCD.ORG_ID_ORGANIZACION)
AND FCL.CTV_CO_ESTADO_DOCUMENTO = 'EM'
AND FCL.ID_REGISTRO = RCD.ID_REFERENCIA
AND FCL.UBG_ID_UBICACION_CLIENTE in (SELECT ID_REGISTRO
FROM S00_UBICACION_GEOGRAFICA
START WITH ID_REGISTRO = nvl(NULL, FCL.UBG_ID_UBICACION_CLIENTE)
CONNECT BY PRIOR ID_REGISTRO = UBG_ID_UBICACION_PADRE)
AND IVA.FAC_ID_FACTURA (+) = FCL.ID_REGISTRO
AND RCO.FAC_ID_FACTURA (+) = FCL.ID_REGISTRO
GROUP BY RCD.CTV_CO_CLASE_ORGANIZACION
,RCD.CTV_DE_CLASE_ORGANIZACION
,RCD.CO_ORGANIZACION
,RCD.ORG_NB_DISTRIBUIDOR
,FCL.PER_CO_IDENTIFICACION_VENDEDOR
,FCL.PER_NB_PRIMER_NOMBRE_VENDEDOR||' '||
FCL.PER_NB_PRIMER_APELLIDO_VEND) COB
WHERE VTA.CO_CLIENTE = DEV.CO_CLIENTE (+)
AND VTA.CO_VENDEDOR = DEV.CO_VENDEDOR (+)
AND VTA.CO_CLIENTE = COB.CO_CLIENTE (+)
AND VTA.CO_VENDEDOR = COB.CO_VENDEDOR (+)
ORDER BY VTA.NB_VENDEDOR
,VTA.CO_CLIENTE
Is there a way i can influence the join method on this query ...?
It's an XE DB.
Regards, Luis ...!THIS IS THE PLAN:
SQL> /
Execution Plan
0 SELECT STATEMENT Optimizer=ALL_ROWS (Cost=79006 Card=1 Bytes
=253)
1 0 SORT (ORDER BY) (Cost=79006 Card=1 Bytes=253)
2 1 HASH JOIN (OUTER) (Cost=79005 Card=1 Bytes=253)
3 2 HASH JOIN (OUTER) (Cost=78538 Card=1 Bytes=211)
4 3 VIEW (Cost=78478 Card=1 Bytes=182)
5 4 HASH (GROUP BY) (Cost=78478 Card=1 Bytes=232)
6 5 FILTER
7 6 HASH JOIN (OUTER) (Cost=78469 Card=1 Bytes=232
8 7 TABLE ACCESS (BY INDEX ROWID) OF 'T04_FACTUR
A_PRODUCTO' (TABLE) (Cost=2 Card=1 Bytes=46)
9 8 NESTED LOOPS (Cost=25 Card=1 Bytes=213)
10 9 VIEW OF 'V04_FACTURA_CLIENTE_TOTAL_R' (V
IEW) (Cost=23 Card=1 Bytes=167)
11 10 NESTED LOOPS (Cost=23 Card=1 Bytes=284
12 11 NESTED LOOPS (OUTER) (Cost=23 Card=1
Bytes=278)
13 12 HASH JOIN (SEMI) (Cost=23 Card=1 B
ytes=272)
14 13 NESTED LOOPS (Cost=17 Card=1 Byt
es=259)
15 14 NESTED LOOPS (Cost=16 Card=1 B
ytes=218)
16 15 NESTED LOOPS (OUTER) (Cost=1
6 Card=1 Bytes=212)
17 16 NESTED LOOPS (Cost=15 Card
=1 Bytes=179)
18 17 NESTED LOOPS (Cost=15 Ca
rd=1 Bytes=173)
19 18 NESTED LOOPS (OUTER) (
Cost=14 Card=1 Bytes=162)
20 19 NESTED LOOPS (OUTER)
(Cost=14 Card=1 Bytes=156)
21 20 NESTED LOOPS (OUTE
R) (Cost=14 Card=1 Bytes=150)
22 21 NESTED LOOPS (OU
TER) (Cost=14 Card=1 Bytes=144)
23 22 NESTED LOOPS (
Cost=14 Card=1 Bytes=105)
24 23 SORT (UNIQUE
) (Cost=2 Card=1 Bytes=13)
25 24 TABLE ACCE
SS (FULL) OF 'T00_GRUPO_DATO_USUARIO_ACTIVO' (TABLE (TEMP))
(Cost=2 Card=1 Bytes=13)
26 23 TABLE ACCESS
(BY INDEX ROWID) OF 'T04_FACTURA' (TABLE) (Cost=11 Card=1 B
ytes=92)
27 26 INDEX (RAN
GE SCAN) OF 'I04_FAC_FE_EMISION' (INDEX) (Cost=10 Card=2)
28 22 TABLE ACCESS (
BY INDEX ROWID) OF 'T03_EMPRESA_SUCURSAL' (TABLE) (Cost=0 Ca
rd=1 Bytes=39)
29 28 INDEX (RANGE
SCAN) OF 'I03_EMS_EMP' (INDEX) (Cost=0 Card=1)
30 21 INDEX (UNIQUE SC
AN) OF 'PK_PRY' (INDEX (UNIQUE)) (Cost=0 Card=1 Bytes=6)
31 20 INDEX (UNIQUE SCAN
) OF 'PK_CAJ' (INDEX (UNIQUE)) (Cost=0 Card=1 Bytes=6)
32 19 INDEX (UNIQUE SCAN)
OF 'PK_PEC' (INDEX (UNIQUE)) (Cost=0 Card=1 Bytes=6)
33 18 TABLE ACCESS (BY INDEX
ROWID) OF 'T00_CONTENIDO_TABLA_VIRTUAL' (TABLE) (Cost=1 Car
d=1 Bytes=11)
34 33 INDEX (UNIQUE SCAN)
OF 'PK_CTV' (INDEX (UNIQUE)) (Cost=0 Card=1)
SORRY EXPLAIN OUTPUT TRUNCATED DUE TO SPACE RESTRICION .....
Any help would be greatly appreciated.
I believe there must be a way to influence on the tha costly HASH JOIN operation
SQL> SPOOL OFF -
My Dear
if I have table like emp table in scott plus new column month_sal
And I write qery like this
select ename,avg(sal) from emp
where month_sal=2
group by ename
no Problem up to now
I need Improve this query to be like this
select ename,avg(sal) current_month,avg(sal) previous_month from emp
where month_sal=2
group by ename
I need make another avgearge but for previuos parametre month
thanks in advanceuser222 wrote:
PLZ I need your helpIt would help if you provided some suitable example data and expected output for us so it was clear what you wanted, as described in the FAQ: {message:id=9360002}
Perhaps this helps...
SQL> ed
Wrote file afiedt.buf
1 with t as (select 1 as item_code, 20 as item_price, 1 as mnth, 2011 as yr from dual union all
2 select 2, 30, 1, 2011 from dual union all
3 select 3, 15, 1, 2011 from dual union all
4 select 4, 7, 2, 2011 from dual union all
5 select 5, 8, 2, 2011 from dual union all
6 select 6, 9, 2, 2011 from dual union all
7 select 7, 10, 2, 2011 from dual union all
8 select 8, 14, 3, 2011 from dual union all
9 select 9, 21, 3, 2011 from dual union all
10 select 10, 7, 4, 2011 from dual union all
11 select 11, 10, 4, 2011 from dual union all
12 select 12, 13, 4, 2011 from dual)
13 --
14 -- end of test data
15 --
16 select mnth, yr, mnth_avg_price
17 ,lag(mnth_avg_price) over (order by yr, mnth) as prev_mnth_avg_price
18 from (
19 select mnth, yr, avg(item_price) as mnth_avg_price
20 from t
21 group by mnth, yr
22 )
23* order by yr, mnth
SQL> /
MNTH YR MNTH_AVG_PRICE PREV_MNTH_AVG_PRICE
1 2011 21.6666667
2 2011 8.5 21.6666667
3 2011 17.5 8.5
4 2011 10 17.5
SQL> -
Hi All,
I create following query which return my required results. but when i insert a new entry in the table it returns a new group of the same month and not add it in the above group where i doing mistake any idea ????
My required results
SQL> SELECT DISTINCT TO_CHAR(T.POS_DATE, 'Month') Month,count(*) Date_rec,sum(t.amount) amount,
2 t.Asset, avg(t.amount) avg_ora_col,Sum(t.amount)/ count(*) "Normal Average"
3 from pos t
4 group by t.pos_date,t.asset;
MONTH DATE_REC AMOUNT ASSET AVG_ORA_COL Normal Average
November 3 750 Loans 250 250
December 2 900 Loans 450 450
SQL> select * from pos;
POS_DATE ASSET AMOUNT
01-NOV-07 Loans 100
01-NOV-07 Loans 250
01-NOV-07 Loans 400
02-NOV-07 Loans 100
02-NOV-07 Loans 250
02-NOV-07 Loans 400
03-NOV-07 Loans 100
03-NOV-07 Loans 250
03-NOV-07 Loans 400
09-DEC-07 Loans 500
09-DEC-07 Loans 400
11 rows selected.
After insertion records in table it looks like following:
SQL> SELECT DISTINCT TO_CHAR(T.POS_DATE, 'Month') Month,count(*) Date_rec,sum(t.amount) amount,
2 t.Asset, avg(t.amount) avg_ora_col,Sum(t.amount)/ count(*) "Normal Average"
3 from pos t
4 group by t.pos_date,t.asset;
MONTH DATE_REC AMOUNT ASSET AVG_ORA_COL Normal Average
November 3 750 Loans 250 250
December 2 900 Loans 450 450
November 1 300 Loans 300 300
December 1 300 Loans 300 300
SQL> select * from pos;
POS_DATE ASSET AMOUNT
01-NOV-07 Loans 100
01-NOV-07 Loans 250
01-NOV-07 Loans 400
02-NOV-07 Loans 100
02-NOV-07 Loans 250
02-NOV-07 Loans 400
03-NOV-07 Loans 100
03-NOV-07 Loans 250
03-NOV-07 Loans 400
09-DEC-07 Loans 500
09-DEC-07 Loans 400
10-DEC-07 Loans 300
27-NOV-07 Loans 300
13 rows selected.
My requirment is following
SQL> SELECT DISTINCT TO_CHAR(T.POS_DATE, 'Month') Month,count(*) Date_rec,sum(t.amount) amount,
2 t.Asset, avg(t.amount) avg_ora_col,Sum(t.amount)/ count(*) "Normal Average"
3 from pos t
4 group by t.pos_date,t.asset;
MONTH DATE_REC AMOUNT ASSET
November 4 637 Loans
December 2 600 Loans I want to divide no. of occurance of dates.
which is 4 in Nov and 2 in dec.
Message was edited by:
53637hi,
try this query
Instead of grouping by t.pos_date group by TO_CHAR(T.POS_DATE, 'Month')
SELECT DISTINCT TO_CHAR(T.POS_DATE, 'Month') Month,count(*) Date_rec,sum(t.amount) amount,
t.Asset, avg(t.amount) avg_ora_col,Sum(t.amount)/ count(*) "Normal Average"
from pos t
group by TO_CHAR(T.POS_DATE, 'Month'),t.asset
hope this will work
Regards,
Sridhar -
Hi Everyone...Please help me with this query...!
Please Help me with this doubt as I am unable to understand the logic...behind this code. It's a begineer level code but I need to understand the logic so that I am able to grasp knowledge. Thank you all for being supportive. Please help me.
//Assume class Demo is inherited from class SuperDemo...in other words class Demo extends SuperDemo
//Volume is a method declared in SuperDemo which returns an integer value
//weight is an integer vairable declared in the subclass which is Demo
class Example
public static void main(String qw[])
Demo ob1=new Demo(3,5,7,9);
//Calling Constructor of Demo which takes in 4 int parameters
SuperDemo ob2=new SuperDemo();
int vol;
vol=ob1.volume();
System.out.println("Volume of ob1 is " + vol);
System.out.println("Weight of ob1 is " + ob1.weight);
System.out.println();
ob2=ob1;
}Can someone please make me understand --- how is this possible and why !
If the above statement is valid then why not this one "System.out.println(ob2.weight);"
Thanks Thanks Thanks!u see the line wherein I am referencing the objectof
a subclass to the superclass...right? then why we
can't do System.out.println(ob2.weight)?You need to distinguish two things:
- the type of the object, which determines with the
object can do
- the type of the reference to the object, which
determines what you see that you can do
Both don't necessarily have to match. When you use a
SuperDemo reference (obj2) to access a Demo instance
(obj1), for all you know, the instance behind obj2 is
of type SuperDemo. That it's in reality of type Demo
is unknown to you. And usually, you don't care -
that's what polymorphism is about.
So you have a reference obj2 of type SuperDemo.
SuperDemo objects don't have weight, so you don't see
it - even though it is there.So from ur explanation wat I understand is - Even though u reference a subclass object to a superclass, u will only be able to access the members which are declared in the superclass thru the same...right
? -
Help with reworking this query
Hi Gurus.
I use the following script on an ad-hoc basis to check free space in tablespaces and it works fine.
However I would like to trim this script so that it outputs to a small file which can then be emailed. I would like the file to only contain the % free column of the original output.
I have tried but failed miserably in an effort to change this query. Can anyone assist?
set lines 200 pages 2000
col tablespace_name heading 'Tablespace' format a30 truncate
col total_maxspace_mb heading 'MB|Max Size' format 9G999G999
col total_allocspace_mb heading 'MB|Allocated' format 9G999G999
col used_space_mb heading 'MB|Used' format 9G999G999D99
col free_space_mb heading 'MB|Free Till Max' like used_space_mb
col free_space_ext_mb heading 'MB|Free Till Ext' like used_space_mb
col pct_used heading '%|Used' format 999D99
col pct_free heading '%|Free' like pct_used
break on report
compute sum label 'Total Size:' of total_maxspace_mb total_allocspace_mb used_space_mb - free_space_mb (used_space_mb/total_maxspace_mb)*100 on report
select /*+ALL_ROWS */
alloc.tablespace_name,
alloc.total_maxspace_mb,
alloc.total_allocspace_mb,
(alloc.total_allocspace_mb - free.free_space_mb) used_space_mb,
free.free_space_mb+(alloc.total_maxspace_mb-alloc.total_allocspace_mb) free_space_mb,
free.free_space_mb free_space_ext_mb,
((alloc.total_allocspace_mb - free.free_space_mb)/alloc.total_maxspace_mb)*100 pct_used,
((free.free_space_mb+(alloc.total_maxspace_mb-alloc.total_allocspace_mb))/alloc.total_maxspace_mb)*100 pct_free
FROM (SELECT tablespace_name,
ROUND(SUM(CASE WHEN maxbytes = 0 THEN bytes ELSE maxbytes END)/1048576) total_maxspace_mb,
ROUND(SUM(bytes)/1048576) total_allocspace_mb
FROM dba_data_files
WHERE file_id NOT IN (SELECT FILE# FROM v$recover_file)
GROUP BY tablespace_name) alloc,
(SELECT tablespace_name,
SUM(bytes)/1048576 free_space_mb
FROM dba_free_space
WHERE file_id NOT IN (SELECT FILE# FROM v$recover_file)
GROUP BY tablespace_name) free
WHERE alloc.tablespace_name = free.tablespace_name (+)
ORDER BY pct_used DESC
SELECT tablespace_name
FROM dba_data_files
WHERE file_id NOT IN (SELECT FILE# FROM v$recover_file)
GROUP BY tablespace_name alloc,
(SELECT tablespace_name,
SUM(bytes)/1048576 free_space_mb
FROM dba_free_space
WHERE file_id NOT IN (SELECT FILE# FROM v$recover_file)
GROUP BY tablespace_name) free
WHERE alloc.tablespace_name = free.tablespace_name (+)
ORDER BY pct_used DESC;
The output from this is:
MB MB MB MB MB % %
Tablespace Max Size Allocated Used Free Till Max Free Till Ext Used Free
APPS_TS_TX_IDX 18,197 17,730
APPS_TS_TX_DATA 25,600 24,832 24,746.38 853.63 85.63 96.67 3.33
APPS_TS_ARCHIVE 2,048 2,048 1,963.00 85.00 85.00 95.85 4.15
APPS_TS_MEDIA 10,240 8,693 8,662.88 1,577.13 30.13 84.60 15.40
I would like to ideally have only the % Free column (at the far right) returned.
Oracle 10.2.0.4
Linux RH 4.
Thanks in advance.
DAI have a simple query for tablespace growth check. try this if it suits for you,
select t1.n1 "Tablespace Name",
t2.total "Total size",
(t2.total-t1.free) "Used Size" ,
t1.free "Free space",
trunc((t1.free/t2.total)*100) "%free " ,
trunc((1-t1.free/t2.total)*100) "% used"
from
(select tablespace_name n1,trunc(sum(bytes)/1024/1024) free
from dba_free_space where tablespace_name not in ('CWMLITE','DRSYS','ODM','XDB','EXAMPLE','TOOLS')
group by tablespace_name ) t1 ,
(select trunc(sum(bytes)/1024/1024) total,tablespace_name n2
from dba_Data_files where tablespace_name not in ('CWMLITE','DRSYS','ODM','XDB','EXAMPLE','TOOLS')
group by tablespace_name) t2
where t1.n1=t2.n2;
Maybe you are looking for
-
Taking Z1 back to shops!! going back to Apple: Sony Bridge for Mac does not work
Been an Iphone owner. really, really wanted to try a good android phone, and the z1 looked the best. However I have had the most frustrating experience- this junky bridge software looks slick but it simply does not work on a mac . I have spent nearl
-
Domain Controllers not replicating
Hi All Domain name: abc.com DC1 - Windows Server 2003 R2 (Physical Server) - 192.168.1.1 DC2 - Windows Server 2012 (Virtual Machine) - 192.168.1.2 Somehow DC1 doesn't replicated to DC2. netdom query fsmo's result: Schema master DC1.abc
-
Hi friends, I have a radio button page item which is showing two values like <li>4 Stars <li>5 Stars I need to show these two radio buttons according to the employee number that is firing on the field Employee Number. Suppose, for an example i need t
-
Finding Photos in LR and Backup Location
Hi, I am a MAC user and currently use a Drobo 5D as my backup system. When I import photos, I always import them to my MAC HD and make a second copy to the DROBO. But sometimes my DROBO gets disconnected and it does not backup to that location. Is th
-
Can't get PS to save a image file...
no matter of which type, in a different file location without PS crashing. Using CC on a Mac using Yosemite 10.10. Not had problem before up until yesterday.