Outer Join or Function
Hi everyone:
I would like to know which one is faster: The outer join or the function a select statement.
Thanks,
As 3360 pointed out above this question is general enough.
But in the motto - everything what can be done in plain SQL should be done in SQL:
SQL> create or replace function my_function(objid in number)
2 return number
3 is
4 obj_type number;
5 begin
6 select object_type_id into obj_type from nc_objects where object_id = objid;
7 return obj_type;
8 end;
9 /
Function created.
Elapsed: 00:00:00.72
SQL> set autotrace traceonly stat
SQL> select (select object_type_id from nc_objects o1 where o1.object_id = o2.object_id) objtype
2 from nc_objects o2
3 /
2092663 rows selected.
Elapsed: 00:02:154.90
Statistics
23 recursive calls
0 db block gets
6563019 consistent gets
23405 physical reads
0 redo size
85627517 bytes sent via SQL*Net to client
15486040 bytes received via SQL*Net from client
139512 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
2092663 rows processed
SQL> select my_function(object_id) from nc_objects;
2092663 rows selected.
Elapsed: 00:03:212.10
Statistics
2092686 recursive calls
0 db block gets
8516178 consistent gets
0 physical reads
0 redo size
85627532 bytes sent via SQL*Net to client
15486040 bytes received via SQL*Net from client
139512 SQL*Net roundtrips to/from client
5 sorts (memory)
0 sorts (disk)
2092663 rows processedRgds.
Similar Messages
-
I have a query as shown below
select w.columns1, w.cloumn2, w.counter
Select a.columns1, a.cloumn2, a.rownum counter
from (subquery a
union
subquery b)
) w
view b
where
w.counter(+) = y.counter,
The view has standard 12 records with a value 0. Now my problem is that for each product_key in main query, if i receive less then 12 records then the oter join with view should halp me to fetch 12 records for a particular product.
But soehow the outer join ins not working.
HELP required ASAP
Thanks in Advance
AjitSELECT
w.CA_NUMBER, W.payment_date, y.counter
from
select /*p.portfolio_id, p.ca_number,p.investor_type_code, p.owner_id,
p.ca_process_date,p.product_month_id,
p.Transaction_Type,p.payment_date,
row_number() OVER (PARTITION BY p.ca_number ORDER BY p.ca_process_date) counter
p.portfolio_id, p.ca_number,p.ca_process_date,p.Transaction_Type,
row_number() OVER (PARTITION BY p.ca_number ORDER BY p.ca_process_date desc) counter,
payment_date
from
-- getting records for both the facility and the fee transaction
-- select records for the facility transaction
SELECT x1.portfolio_id, x1.ca_number,x3.investor_type_code, x4.owner_id, x2.ca_process_date,x1.product_month_id,
'CA' Transaction_Type,x2.ca_effective_date payment_date
FROM dls_dm.ca_transaction_fact x,
dls_dm.ca_product_dimension x1,
dls_dm.ca_transaction_dimension x2,
dls_dm.investor_dimension x3,
dls_dm.owner_dimension x4,
dls_rep.adm_acbs_periods x5
WHERE ( (x1.product_key = x.product_key) )
AND (x2.transaction_key = x.transaction_key)
AND (x3.investor_key = x.investor_key)
AND (x4.owner_key = x.owner_key)
AND (x1.product_month_id = 200508)
-- to be removed later AND (x1.product_month_id = to_char(x5.Last_processing_date,'yyyymm'))
-- and x1.ca_number = '0000000215'
Union all
-- select records for the facility transaction
SELECT x1.portfolio_id, x1.ca_number,x3.investor_type_code, x4.owner_id, x2.process_date,x1.product_month_id,
'FEE' Transaction_Type, x2.effective_date payment_date
FROM dls_dm.ca_fee_transaction_fact x,
dls_dm.ca_product_dimension x1,
dls_dm.fee_transaction_dimension x2,
dls_dm.investor_dimension x3,
dls_dm.owner_dimension x4,
dls_rep.adm_acbs_periods x5
WHERE ( (x1.product_key = x.product_key) )
AND (x2.transaction_key = x.transaction_key)
AND (x3.investor_key = x.investor_key)
AND (x4.owner_key = x.owner_key)
AND (x1.product_month_id = 200508)
-- to be removed later AND (x1.product_month_id = to_char(x5.Last_processing_date,'yyyymm'))
--and x1.ca_number = '0000000215'
)p
ORDER BY p.ca_number ASC, p.ca_process_date DESC
)W,
dls_dm.test_view y
where w.counter(+) = y.counter
and w.counter <=12
order by 1,3
the code for y starts from here
CREATE OR REPLACE FORCE VIEW DLS_DM.TEST_VIEW
(CA_NUMBER, PAYMENT_DATE, COUNTER)
AS
select CA_NUMBER, payment_date, counter
from
select 1 counter, 0 payment_date, '' CA_NUMBER from dual
union
select 2 counter, 0 payment_date, '' CA_NUMBER from dual
union
select 3 counter, 0 payment_date,'' CA_NUMBER from dual
union
select 4 counter, 0 payment_date,'' CA_NUMBER from dual
union
select 5 counter, 0 payment_date,'' CA_NUMBER from dual
union
select 6 counter, 0 payment_date, '' CA_NUMBER from dual
union
select 7 counter, 0 payment_date, '' CA_NUMBER from dual
union
select 8 counter, 0 payment_date, '' CA_NUMBER from dual
union
select 9 counter, 0 payment_date, '' CA_NUMBER from dual
union
select 10 counter, 0 payment_date, '' CA_NUMBER from dual
union
select 11 counter, 0 payment_date, '' CA_NUMBER from dual
union
select 12 counter, 0 payment_date, '' CA_NUMBER from dual
) y; -
Left outer join functions like simple join
I created two views SCO_REQGROSSLINES_V & SCO_REQLINESCOMPLETE on Oracle requisitions base tables. Our business rules enforce the following identity: the number of gross requisition lines will always be greater than or equal to the number of requisition lines complete. (By complete I mean delivered.)
Each view has a key named DATESUBINV_KEY constructed of a transaction date and the subinventory code using this logic:
, TO_CHAR(TRUNC(transaction_date),'YYYYMMDD') || subinventory_code
On 03-SEP-2010 a user created a requisition with one line item for material from the HEAT subinventory which was not delivered. This row is retuned in the result set when I query on SCO_REQGROSSLINES_V but is NOT returned when I query on SCO_REQLINESCOMPLETE. So far so good.
When I issue either of the the following left outer joins I do not get the row for the row for the HEAT subinventory on 03-SEP-2010:
select rgl.trxn_date
, rgl.subinventory
, rgl.line_count gross_line_count
, rgl.ext_prc gross_value
, rlc.line_count lines_filled
, rlc.ext_prc lines_filled_value
from SCO_REQGROSSLINES_V rgl left outer join sco_reqlinescomplete_v rlc
ON rgl.datesubinv_key = rlc.datesubinv_key
where rgl.TRXN_DATE BETWEEN to_date('29-AUG-2010') AND to_date('04-SEP-2010')
and rlc.trxn_date BETWEEN to_date('29-AUG-2010') AND to_date('04-SEP-2010')
order by rgl.trxn_date, rgl.subinventory
select rgl.trxn_date, rgl.subinventory
, rgl.line_count gross_line_count
, rgl.ext_prc gross_value
, rlc.line_count lines_filled
, rlc.ext_prc lines_filled_value
from SCO_REQGROSSLINES_V rgl
, sco_reqlinescomplete_v rlc
where rgl.TRXN_DATE BETWEEN to_date('29-AUG-2010') AND to_date('04-SEP-2010')
and rlc.trxn_date BETWEEN to_date('29-AUG-2010') AND to_date('04-SEP-2010')
AND rgl.datesubinv_key = rlc.datesubinv_key(+)
order by rgl.trxn_date, rgl.subinventory
Question: Why would the left outer joins function as a simple join on DATESUBINV_KEY? Do keys on views function differently than keys defined in the data dictionary? If they do how can I make these keys to function like data dictionary keys?Hi,
The WHERE clause is applied after the outer join is completed. In your example, rows from rgl will be in the result set even if they have no match in rlc. In those cases, all the columns from rlc will be NULL.
Okay, so you have these rows that contain data from rgl but NULLs where the data from rlc was supposed to go. Now it's time to start the WHERE clause. You then apply conditions like this in the WHERE clause:
AND rlc.trxn_date BETWEEN ...NULL is between anything, so the row that the outer join prodeuced is rejected.
All conditions involivn columns from rlc probably need to be part of the join condition, not the WHERE clause.
For example, in you first query the FROM and WHERE clauses might be:
FROM sco_reqgrosslines_v rgl
LEFT OUTER JOIN sco_reqlinescomplete_v rlc ON rgl.datesubinv_key = rlc.datesubinv_key
AND rlc.trxn_date BETWEEN TO_DATE ( '29-AUG-2010'
, 'DD-MON-YYYY'
AND TO_DATE ( '04-SEP-2010'
, 'DD-MON-YYYY'
WHERE rgl.trxn_date BETWEEN TO_DATE ( '29-AUG-2010'
, 'DD-MON-YYYY'
AND TO_DATE ( '04-SEP-2010'
, 'DD-MON-YYYY'
)Always use (at least) two arguments when calling TO_DATE.
Conditions that only involve rgl can be in the WHERE clause, but if any conditions from rlc are in the WHERE clause, then the effect will be the same as an inner join.
There no difference between tables and views (or sub-queries) in this regard: the same thing would happen regardless of whether rgl and rlc were really tables or not. -
Hello
I am trying to translate the following Sybase Query to Oracle . I am running the query on a 10gR1 database.
The problem is with the NVL clause on the join I am getting a runtime exception .
Is there a way to re-write this query without breaking the functionality.
SELECT t1.*,
NVL(t2.Branch_name, t3.Branch_name)
FROM table1 t1
LEFT OUTER JOIN
table2 t2
ON (t1.Account_id = t2.Account_id)
LEFT OUTER JOIN
table3 t3
ON (t1.Account_id = t3.Account_id)
LEFT OUTER JOIN
table4 t4
ON (NVL(t2.Branch_Name, t3.Branch_Name) = t4.cost_centre);
ThanksThe original query had a insert statement and it was failing with ORA-01400 even though the select query fetched 0 rows
Insert into Branch_Master
SELECT t1.*,
NVL(t2.Branch_name, t3.Branch_name)
FROM table1 t1
LEFT OUTER JOIN
table2 t2
ON (t1.Account_id = t2.Account_id)
LEFT OUTER JOIN
table3 t3
ON (t1.Account_id = t3.Account_id)
LEFT OUTER JOIN
table4 t4
ON (NVL(t2.Branch_Name, t3.Branch_Name) = t4.cost_centre);
ksedmp: internal or fatal error
ORA-01400: cannot insert NULL into ("<<schema_name>>"."Branch_Master"."BRANCH_NAME")
I have re-written the query using a Inline view . Can you please review and let me know if it is ok
select * from
( SELECT t1.*,
NVL(t2.Branch_name, t3.Branch_name) Branch_name_final
FROM table1 t1
LEFT OUTER JOIN
table2 t2
ON (t1.Account_id = t2.Account_id)
LEFT OUTER JOIN
table3 t3
ON (t1.Account_id = t3.Account_id) ) IV_Temp
LEFT OUTER JOIN Table4 on (IV_temp.Branch_name_final = T4.cost_centre ; -
How to achieve an outer join with existsNode() function
I have a requirement to do an outer join with existsNode() function in my where clause. At present my where clause for join is like below
WHERE A.SOME_ID= “XYZ”
AND existsNode (B.SOMEXML_FEILD , …. ) = 1
AND existsNode (C.SOMEOTHERXML_FEILD , …. ) = 1
In this case if the existsNode fails on B or C, I still want data from A to be selected. How to rewrite this query to achieve that? I kinda want to achieve an outer joinHi,
is this what you are looking for:
SQL> with t as(select 1 id1,'A' name from dual union all
2 select 2 ,'B' name from dual union all
3 select 3,'C' from dual)
4 ,x as(select 1 id2,xmltype('<a>a</a>') xcol from dual union all
5 select 2 ,xmltype('<b>b</b>') xcol from dual)
6 select *
7 from t,x
8 where t.id1=x.id2(+)
9 and (existsNode(x.xcol,'/a')=1 or x.xcol is null);
ID1 N ID2 XCOL
1 A 1 <a>a</a>
3 C
SQL> spool off; -
Outer Join or Row-Level Function
Hi ALL,
I have a query which involves five tables T1, R1, R2, R3 and R4. T1 is a transaction table, whereas R1, R2, R3 and R4 are reference tables (Parent tables, with foreign keys defined in T1). T1 table always contains R1 and R2 referenced data. BUT T1 table may contain sometimes NULL for R3 and R4.
Now my question is simple;
Should i use an OUTER Join for R3 and R4 in the query? like
<code>
select T1.col1, R1.col2, R2.col2, R3.col2, R4.col2
from T1, R1, R2, R3, R4
where T1.col2 = R1.col1
and T1.col3 = R2.col1
and T1.col4 = R3.col1(+)
and T1.col5 = R4.col1(+)
</code>
OR
Should i use row-level functions for R3 and R4, like
<code>
select T1.col1, R1.col2, R2.col2,
(Select R3.col2 from R3 where R3.col1 = T1.col4),
(Select R4.col2 from R4 where R4.col1 = T1.col5)
from T1, R1, R2
where T1.col2 = R1.col1
and T1.col3 = R2.col1
</code>
which approach is better and why?
Records in T1 = 2,000,000
Records in R1 = 1000
Records in R2 = 300
Records in R3 = 1800
Records in R4 = 200
Please note that all foreign keys are indexed, there are primary keys in all R tables
Thanks,
QQ.dwh_10g wrote:
I have preferred to go for Outer Joins, as there might be a possibility, if data grows than there will be more row-level scans; hence slower output in future.
If i go with a row-level scan, then there will be more usage of Hash tables (Memory), so if more memory is required and our SGA limits is crossed, then there will be more disk I/O i guess. which is a costly operation.
QQ,
as already explained, unfortunately it's hard to predict how the "row-level" approach is going to perform in case of increased data volume. Since it is dependent on some factors it could be faster or slower than the outer join approach.
You shouldn't worry too much about the size of the in-memory table. You haven't mentioned your version, but since your alias is "dwh10g" is assume you're using 10g.
In 10g the size is defined by the hidden parameter "_query_execution_cache_max_size" and set to 65536 bytes by default. In pre-10g the size is always 256 entries which might grow bigger than 64k in case you have large input/output values (e.g. large VARCHAR2 strings). Compared to potentially multiple several megabytes large sort and/or hash SQL work areas used by each open cursor this table seems to be relatively small.
I don't think that this memory is taken from the SGA, but belongs to the PGA of the process executing the query and therefore it should not allocate SGA memory (I think even in Shared Server configuration this part should be allocated from the PGA of the shared server process).
So in summary if your data volume increases it shouldn't have an noticeable impact on the memory usage of the "row-level" approach, and therefore this I think is negligible.
But as a recommendation I would say, since the "row-level" approach doesn't seem to be significantly faster than the "outer join" approach and it's behaviour in future is hard to predict (e.g. it could become worse if your data pattern changes or the execution plan changes and therefore the order of the row processing changes) I would stick to the "outer-join" approach. I assume it could be more stable in terms of performance.
Regards,
Randolf
Oracle related stuff blog:
http://oracle-randolf.blogspot.com/
SQLTools++ for Oracle (Open source Oracle GUI for Windows):
http://www.sqltools-plusplus.org:7676/
http://sourceforge.net/projects/sqlt-pp/ -
Need to adjust SQL query for left outer join in Crystal Reports 2008.
I need to change this SQL 2005 query.....
SELECT omnicell_anl.DeviceIDsLastMetricTable.member_id, omnicell_anl.DeviceIDsLastMetricTable.[Device Name],
omnicell_anl.DeviceIDsLastMetricTable.Account, omnicell_anl.labeledLastMetrics.PROPERTY_NAME,
omnicell_anl.labeledLastMetrics.latest_monitor_value
FROM omnicell_anl.DeviceIDsLastMetricTable LEFT OUTER JOIN
omnicell_anl.labeledLastMetrics ON omnicell_anl.DeviceIDsLastMetricTable.member_id = omnicell_anl.labeledLastMetrics.member_id
WHERE
omnicell_anl.labeledLastMetrics.PROPERTY_NAME = ?MyProperty
To this query in Crystal Reports Report Writer:
SELECT omnicell_anl.DeviceIDsLastMetricTable.member_id, omnicell_anl.DeviceIDsLastMetricTable.[Device Name],
omnicell_anl.DeviceIDsLastMetricTable.Account, omnicell_anl.labeledLastMetrics.PROPERTY_NAME,
omnicell_anl.labeledLastMetrics.latest_monitor_value
FROM omnicell_anl.DeviceIDsLastMetricTable LEFT OUTER JOIN
omnicell_anl.labeledLastMetrics ON omnicell_anl.DeviceIDsLastMetricTable.member_id = omnicell_anl.labeledLastMetrics.member_id AND
omnicell_anl.labeledLastMetrics.PROPERTY_NAME = ?MyProperty
I can't seem to get the left outer join function of Crystal Reports to emulate the same SQL query in SQL 2005. Any ideas on how I can create this same query in Crystal 2008?
Thanks,
Dominic
Edited by: Dominic Carissimi on Oct 28, 2008 7:55 PM
Edited by: Dominic Carissimi on Oct 28, 2008 7:56 PMIf you want the list of values for command level parameter then you need to add another command like
select PropertyField from table
and delete the links between this command and the existing command.
Now go to field explorer and edit the command level parameter and make it as dynamic and add the property field from newly added command.
Hope this helps!
Raghavendra -
SCORE(n) returning zero values in an outer join query
Hello all,
Is there any way to get a query that contains an outer join to return proper scores. I couldn't find out why this was happening in my query, but I'm getting a score values of 0 on most results.
Below are queries with result sets. As you can see the results that are scoring in the second query are scoring correctly, but only two have scores.
- - - Query 1, no outer join - - -
SELECT DISTINCT SCORE(0) AS scr,
file_repository.file_id,
file_repository.file_title
FROM file_repository
WHERE CONTAINS(index_url,'SYN(dui,a_thesaurus)', 0) > 0
ORDER BY scr ASC
SCR FILE_ID FILE_TITLE
7 136 Prisoners
7 240 Drug booklet
8 64 Communications
8 146 Rates
8 168 Vehicle Collisions
8 206 document4
14 207 document5
14 211 document5
15 74 Diplomatic Personnel
22 214 documentB
30 81 DUI and PCA Offences
- - - Query 2, with outer join - - -
SELECT DISTINCT SCORE(0) AS scr,
file_repository.file_id,
file_repository.file_title
FROM file_repository, file_security
WHERE CONTAINS(index_url,'SYN(dui,a_thesaurus)', 0) > 0
AND file_repository.file_id = file_security.file_id(+)
AND file_security.auth_id = 0
ORDER BY scr asc
SCR FILE_ID FILE_TITLE
0 74 Diplomatic Personnel
0 81 DUI and PCA Offences
0 136 Prisoners
0 146 Rates
0 168 Vehicle Collisions
0 206 document4
0 207 document5
0 214 documentB
0 240 Drug booklet
8 64 Communications
14 211 document5
This is on Oracle 9i using Oracle Text.
Thanks in advanceTo do this wouldn't you need to know the data in advance? The real source table had 1800 organisations and 8,000,000 transactions.
I Tried this as well, creating a pl/sql package as follows.
create or replace PACKAGE stack AS
TYPE gnt_push_numbers IS TABLE OF NUMBER INDEX BY PLS_INTEGER;
TYPE gvt_push_varchars IS TABLE OF VARCHAR(1000) INDEX BY PLS_INTEGER;
gna_push_numbers gnt_push_numbers;
gva_push_varchars gvt_push_varchars;
FUNCTION PUSH ( pn_push_var NUMBER, pn_offset NUMBER) RETURN NUMBER DETERMINISTIC;
FUNCTION PUSH ( pv_push_var VARCHAR, pn_offset NUMBER) RETURN VARCHAR DETERMINISTIC;
FUNCTION POP_NUM ( pn_offset NUMBER) RETURN NUMBER DETERMINISTIC;
FUNCTION POP_VAR ( pn_offset NUMBER) RETURN VARCHAR DETERMINISTIC;
END stack;
CREATE OR REPLACE
PACKAGE BODY "STACK" AS
FUNCTION push(pn_push_var NUMBER, pn_offset NUMBER) RETURN NUMBER deterministic IS
BEGIN
gna_push_numbers(pn_offset) := pn_push_var;
RETURN pn_push_var;
END push;
FUNCTION push(pv_push_var VARCHAR, pn_offset NUMBER) RETURN VARCHAR deterministic IS
BEGIN
gva_push_varchars(pn_offset) := pv_push_var;
RETURN pv_push_var;
END push;
FUNCTION pop_num(pn_offset NUMBER) RETURN NUMBER deterministic IS
BEGIN
RETURN gna_push_numbers(pn_offset);
END pop_num;
FUNCTION pop_var(pn_offset NUMBER) RETURN VARCHAR deterministic IS
BEGIN
RETURN gva_push_varchars(pn_offset);
END pop_var;
END stack;
Unfortunately it appears to act before the rows are sorted, so will only work in specialised circumstances, in that you have to ensure the rows have been sorted before the function is used.
SELECT PUSH(COL), POP..(COL)
FROM ( SELECT etc.
Luckily the client decided they didn't want to mix their graphs any more so a more classic approach using a base table select for actuals and then a date table select with a sub-query columns for the projection provided a simple solution. -
Dynamic From statement in select query and/or outer join not working
Dear Experts, I have a select query where the select columns are dynamic, the where condition is also dynamic. It is of the below format:
Select (dynamic columns) INTO <wa>
FROM a inner join b on af1 = bf1
inner join c on af2 = cf2......
WHERE (dynamic conditios)
ORDER BY ( dynamic sort condition).
Now I have to include some tables (dynamically depending on the user input) in the inner join statement which will give description for the selected fields. And these database tables may or may no be empty. So in this case, my select query will not return any data if these tables are empty. And I dont want that.
I tried using outer join for the extra tables but it gave me a runtime error. I also tried forming the inner join statement dynamically but it was not supporting.
Kindly give me pointers.
ThanksHey thanks for the reply, but the problem is not solved.
I am already using ( fileds, value) like table in my where condition and the select statement was working properly.
the problem is that now I have to include some tables in the join statement which can be empty and so i want to use Outer join.
But I am getting a runtime error as below:
Error analysis
An exception occurred that is explained in detail below.
The exception, which is assigned to class 'CX_SY_DYNAMIC_OSQL_SYNTAX', was not
caught in
procedure "ZATSCSNG_RFC_READ_TABLE" "(FUNCTION)", nor was it propagated by a
RAISING clause.
Since the caller of the procedure could not have anticipated that the
exception would occur, the current program is terminated.
The reason for the exception is:
The running ABAP program wanted to execute a SELECT statement whose
WHERE condition was (partly) specified dynamically. The part that is
specified in an internal table at runtime is compared to a field of the
right table of an LEFT OUTER JOIN. Such comparisons are not supported by
all database systems and are therefore not allowed. -
Create a view that limits a large table, but also allows an outer join ?
oracle 10.2.0.4
CREATE TABLE MY_PAY_ITEMS
( EMP VARCHAR2(8) NOT NULL
, PAY_PRD VARCHAR2(8) NOT NULL
, KEY1 VARCHAR2(8) NOT NULL
, KEY2 VARCHAR2(8) NOT NULL
, LN_ITEM VARCHAR2(4) NOT NULL
, ITEM_AMT NUMBER(24,2) NOT NULL
, FILLER VARCHAR2(100) NOT NULL)
INSERT INTO MY_PAY_ITEMS
SELECT A.EMP
, B.PAY_PRD
, C.KEY1
, D.KEY2
, E.LN_ITEM
, F.ITEM_AMT
FROM (SELECT TO_CHAR(ROWNUM, '00000000') "EMP" FROM DUAL CONNECT BY LEVEL <= 50 ) A
, (SELECT '2010-' || TO_CHAR(ROWNUM,'00') "PAY_PRD" FROM DUAL CONNECT BY LEVEL <= 52) B
, (SELECT TO_CHAR(ROWNUM, '000') "KEY1" FROM DUAL CONNECT BY LEVEL <= 8) C
, (SELECT TO_CHAR(ROWNUM, '000') "KEY2" FROM DUAL CONNECT BY LEVEL <= 5) D
, (SELECT TO_CHAR(ROWNUM,'000') "LN_ITEM" FROM DUAL CONNECT BY LEVEL <= 20) E
, (select round(DBMS_RANDOM.VALUE * 400,2) "ITEM_AMT" from dual) F
CREATE UNIQUE INDEX MY_PAY_ITEMS ON MY_PAY_ITEMS (EMP, PAY_PRD, KEY1, KEY2, LN_ITEM)
CREATE TABLE MY_ITEM_DISPLAY
( DISPLAY_CODE VARCHAR2(4) NOT NULL
, SEQUENCE NUMBER(2) NOT NULL
, COLUMN_ITEM1 VARCHAR2(4) not null
, COLUMN_ITEM2 VARCHAR2(4) not null
, COLUMN_ITEM3 VARCHAR2(4) not null
, COLUMN_ITEM4 VARCHAR2(4) not null)
INSERT INTO MY_ITEM_DISPLAY VALUES ('01',10,'001','003','004','005');
INSERT INTO MY_ITEM_DISPLAY VALUES ('01',20,'007','013','004','009');
INSERT INTO MY_ITEM_DISPLAY VALUES ('01',30,'001','004','009','011');
INSERT INTO MY_ITEM_DISPLAY VALUES ('01',40,'801','304','209','111');
INSERT INTO MY_ITEM_DISPLAY VALUES ('02',10,'001','003','004','005');
INSERT INTO MY_ITEM_DISPLAY VALUES ('02',20,'007','013','004','009');
INSERT INTO MY_ITEM_DISPLAY VALUES ('02',30,'001','004','009','011');
MY_PAY_ITEMS is a table that stores payslip line items. It has a total size of 500,000,000 rows.
EMP is the unique employee id, We have approx 200,000 employees (with approx 50,000 being active today).
PAY_PRD is a weekly pointer (2010-01, 2010-02 ... 2010-52), we have data from 2004 and are adding a new pay period every week. 2010-01 is defined as the first monday in 2010 to the first sunday in 2010 etc.
KEY1 is an internal key, it tracks the timeline within the pay period.
KEY2 is a child of KEY1, it tracks the sequence of events within KEY1.
LN_ITEM is the actual pay item that resulted from the event on average a person generates 20 rows per event. Note that in this example everybody gets the same LN_ITEM values, but in practice it is 20 selected from 300
ITEM_AMT is the net pay for the line item.
FILLER is an assortment of fields that are irrelevant to this question, but do act as a drag on any row loads.
MY_ITEM_DISPLAY is a table that describes how certain screens should display items. The screen itself is a 4 column grid, with the contents of the individual cells being defined as a lookup of LN_ITEMS to retrieve the relevant LN_AMT.
We have an application that receives a DISPLAY_CODE and an EMP. It automatically creates a sql statement along the lines of
SELECT * FROM MY_VIEW WHERE DISPLAY_CODE = :1 AND EMP = :2
and renders the output for the user.
My challenge is that I need to rewrite MY_VIEW as follows:
1) Select the relevant rows from MY_ITEM_DISPLAY where DISPLAY_CODE = :1
2) Select the relevant all rows from MY_PAY_ITEMS that satisfy the criteria
a) EMP = :2
b) PAY_PRD = (most recent one for EMP as at sysdate, thus if they last got paid in 2010-04 , return 2010-04)
c) KEY1 = (highest key1 within EMP and PAY_PRD)
d) KEY2 = (highest key2 within EMP, PAY_PRD and KEY1)
3) I then need to cross reference these to create a tabular output
4) Finally I have to return a line of 0's where no LN_ITEMs exist ( DISPLAY_CODE 01, sequence 40 contains impossible values for this scenario)
The below query does part of it (but not the PAY_PRD, KEY1, KEy2 )
select * from (
SELECT A.DISPLAY_CODE
, B.EMP
, A.SEQUENCE
, MAX(DECODE(B.LN_ITEM, A.COLUMN_ITEM1, B.ITEM_AMT, 0)) "COL1"
, MAX(DECODE(B.LN_ITEM, A.COLUMN_ITEM2, B.ITEM_AMT, 0)) "COL2"
, MAX(DECODE(B.LN_ITEM, A.COLUMN_ITEM3, B.ITEM_AMT, 0)) "COL3"
, MAX(DECODE(B.LN_ITEM, A.COLUMN_ITEM4, B.ITEM_AMT, 0)) "COL4"
FROM MY_ITEM_DISPLAY A, MY_PAY_ITEMS B
WHERE B.PAY_PRD = '2010-03'
GROUP BY A.DISPLAY_CODE, B.EMP, A.SEQUENCE)
WHERE DISPLAY_CODE = '01'
AND EMP = '0000011'
ORDER BY SEQUENCE
My questions
1) How do I do the PAY_PRD, KEY1, KEY2 constraint, can I use some form of ROW_NUMBER() OVER function ?
2) How do I handle the fact that none of the 4 column LN_ITEMS may exist (see sequence 40, none of those line items can exist)... Ideally the above SQL should return
01, 0000011, 10, <some number>, <some number>, <some number>, <some number>
01, 0000011, 20, <some number>, <some number>, <some number>, <some number>
01, 0000011, 30, <some number>, <some number>, <some number>, <some number>
01, 0000011, 40, 0 , 0 , 0 , 0
I tried a UNION, but his prevented the view from eliminating the bulk of the MY_PAY_ITEMS rows, as it resolve ALL of MY_PAY_ITEMS instead of just retrieving rows for the one EMP passed to the view. The same seems to be true for any outer joins.Hi, if i understood you properly, you need :
select nvl(q.display_code,lag(q.display_code) over (order by rownum)) display_code,
nvl(q.emp,lag(q.emp) over (order by rownum)) emp,
m.s,
nvl(q.COL1,0) COL1,
nvl(q.COL2,0) COL2,
nvl(q.COL3,0) COL3,
nvl(q.COL4,0) COL4,
nvl(PAY_PRD,lag(q.PAY_PRD) over (order by rownum)) PAY_PRD,
nvl(KEY1,lag(q.KEY1) over (order by rownum)) KEY1,
nvl(KEY2,lag(q.KEY2) over (order by rownum)) KEY2
from(
select d.display_code,
t.emp,
d.sequence,
max(DECODE(t.LN_ITEM, d.COLUMN_ITEM1, t.ITEM_AMT, 0)) keep (dense_rank first order by to_date(t.pay_prd,'yyyy-mm') desc ) "COL1",
max(DECODE(t.LN_ITEM, d.COLUMN_ITEM2, t.ITEM_AMT, 0)) keep (dense_rank first order by to_date(t.pay_prd,'yyyy-mm') desc ) "COL2",
max(DECODE(t.LN_ITEM, d.COLUMN_ITEM3, t.ITEM_AMT, 0)) keep (dense_rank first order by to_date(t.pay_prd,'yyyy-mm') desc ) "COL3",
max(DECODE(t.LN_ITEM, d.COLUMN_ITEM4, t.ITEM_AMT, 0)) keep (dense_rank first order by to_date(t.pay_prd,'yyyy-mm') desc ) "COL4",
max(t.PAY_PRD) PAY_PRD,
max(t.key1) keep (dense_rank first order by to_date(t.pay_prd,'yyyy-mm') desc ) key1,
max(t.key2) keep (dense_rank first order by to_date(t.pay_prd,'yyyy-mm') desc ) key2
from MY_PAY_ITEMS t
join MY_ITEM_DISPLAY d
on d.display_code = '01'
where t.emp = '00000011'
group by d.display_code, t.emp, d.sequence
) q
full outer join (select level*10 s from dual connect by level <= 4) m
on m.s = q.sequence
DISPLAY_CODE
EMP
S
COL1
COL2
COL3
COL4
PAY_PRD
KEY1
KEY2
01
00000011
10
101.1
103.1
104.1
105.1
2010-03
008
005
01
00000011
20
107.1
113.1
104.1
109.1
2010-03
008
005
01
00000011
30
101.1
104.1
109.1
111.1
2010-03
008
005
01
00000011
40
0
0
0
0
2010-03
008
005
Ramin Hashimzade -
Outer join problem (ORA-01799)
We have a database design roughly as follows:
- A STAFF table (columns don't matter here).
- Resources have a cost per hour that varies over time, so we have a STAFF_COST table with an effective date and a cost per hour
- A PROJECT table (columns don't matter here).
- Projects can have staff assigned, so we have a PROJECT_STAFF table which has foreign keys to the PROJECT and STAFF table.
- Project staff have a cost per hour, which can vary over time, and be different to the (default) staff costs. So we have a PROJECT_STAFF_COST table which uses the PROJECT_STAFF foreign key, with an effective date and a cost per hour
- Staff work on tasks so we have a TIMESHEET_TASK and TIMESHEET_DAY tables which define a project worked on, task within the project (optional as time can be 'entered against the project', who is recording the time, the hours worked and the day the hours were worked.
So when timesheet information is entered we have three scenario's that we need to cover.
1) The resource is a member of the project and the hours were worked on a day for which we have a project staff cost. That is, the project staff cost table has one or more rows for the staff member assigned to the given project with an effective date before the date the hours were entered against.
2) The resource is a member of the project but the hours were worked on a day for which we do not have a project staff cost. That is, the project staff cost table has one or more entries for the staff member assigned to the given project, but all the effective dates are after the date the hours were entered against.
3) The resource is not a member of the project. That is, the project staff cost table does not have any rows for the staff member. Time was entered 'against the project'.
We need to work out the actual cost of the project. So we need to retrieve every day's timesheet entry, returning the hours assigned and the cost per hour relevant for that day. I have the following query:
select tsh.staff_id, s.full_name, tsd.entry_date, tsd.hours as ProjectHours,
psCOST_INFO.cost_per_hour as ProjectCost
from timesheet_day tsd
inner join timesheet_task tst on tst.timesheet_task_id = tsd.timesheet_task_id
inner join timesheet_header tsh on tst.timesheet_header_id = tsh.timesheet_header_id
inner join staff s on s.staff_id = tsh.staff_id
left join (Select ps.project_id, ps.staff_id, psc.project_staff_id, psc.effective_date, psc.cost_per_hour
from project_staff ps
inner join project_staff_cost psc on ps.project_staff_id = psc.project_staff_id) as psCOST_INFO
on psCOST_INFO.staff_id = tsh.staff_id and psCOST_INFO.project_id = tst.project_id
and psCOST_INFO.effective_date = (select max(ps2.effective_date) from project_staff_cost ps2
where ps2.project_staff_id = psCOST_INFO.project_staff_id
and ps2.effective_date <= tsd.entry_date)
where tst.project_id = 55825
Using the left join covers scenario's 2 and 3 above because I will get null in the cost columns and can then take appropriate action. If I were to use an inner join, then hours in timesheets from scenario's 2 and 3 would be excluded, which is not what we want.
The subselect using the MAX aggregate function is required to get the cost per hour most relevant for the timesheet day. That is, if there are several effective dates for the project staff member before the date in question, we want the most recent one. We can't just use the MAX one, however in case there is an effective date after the particular timesheet date. Sheesh...
This query works fine in SQL Server. It it not allowed in Oracle and returns an ORA-01799 column may not be outer joined to a subquery.
I'm not going to bother to ask why not. I just need a way to do what I want. I've spent days trying to move the code around but I either end up with an inner join (which returns fewer rows than I want) or it just plain don't work.
Can someone help me rework this query to achieve the result I want?
Thanks, AndrewThanks for your reply, Laurent. In my experience trying to cut important corners in explaining a problem only serves to make it more difficult to solve. That pretty much was the smallest reproducable query that demonstrates the complexity of the problem I have. I'm not just trying to get which publishers live in the 'CA' state here...
From what I have just read about rank() it serves the same purpose as max() on a given column, and getting the maximum or top ranked one just doesn't cut it. As I said in my original post that provided all the relevant (and no spurious) information on the problem, it is possible that there are effective dates AFTER the date we are interested in and they have to be excluded.
I have to get the project staff cost row with the latest date that is before the timesheet date. That means I have to reference data in the outer query. Oracle seems to have a problem with that when used in an outer join.
We are currently going down the track of 3 UNION'd statement to cover the 3 scenario's. A single query would be more efficient so if anyone can provide guidance I would appreciate it.
Thanks, Andrew -
Defaulting Null Values in an outer join to the last joined row's values.
I have a situation where I need to fill in the missing values from an outer join with the last values returned by the join.
The query is based on a date table, an organization table and a transaction table.
SELECT D.DATE_ID, O.ORG_ID, T.VALUE
FROM D_ORGANIZATION O, D_DATE D, F_TRANSACTION T
WHERE D.DATE_ID = T.DATE_ID(+)
AND T.ORG_ID = O.ORG_ID(+)
AND O.ORG_NAME = '&NAME'[
AND D.THE_DATE >= ADD_MONTHS( TO_DATE( '&&PERIOD_DATE', 'DD-MON-YYYY' ), -23 )
AND D.THE_DATE <= ADD_MONTHS( TO_DATE( '&&PERIOD_DATE', 'DD-MON-YYYY' ), 24 )
So the query will return all dates in the 4 year period, and where transactions exist the relevent value.
DATE_ID ORG_ID VALUE
38291 2 99.8
38321 2 45.1
38352
38383
38411
What I need to happen is:
DATE_ID ORG_ID VALUE
38291 2 99.8
38321 2 45.1
38352 2 45.1
38383 2 45.1
38411 2 45.1
Lag appears to be of no use because it will only pick up the last genuine value, so using
NVL(T.VALUE, LAG(T.VALUE,1) OVER ( .... )
Gives:
ATE_ID ORG_ID VALUE
38291 2 99.8
38321 2 45.1
38352 2 45.1
38383
38411
The length of the data gap can vary as constituent organisations don't all return their data at the same time, and there may be intermediate dates where no data is returned , but the value needs to be calculated.
What's going on here is that a gaph is being generated where the tool requires data points to plot the line, once the real data ends a bespoke trend calculations takes over based on the last value returned. I do not have access to the data warehousing options so a solution that doen't need them would be handy, but if not then options can be purchased.
The tool can't use PL/SQL, but is perhaps a bespoke function in order?To do this wouldn't you need to know the data in advance? The real source table had 1800 organisations and 8,000,000 transactions.
I Tried this as well, creating a pl/sql package as follows.
create or replace PACKAGE stack AS
TYPE gnt_push_numbers IS TABLE OF NUMBER INDEX BY PLS_INTEGER;
TYPE gvt_push_varchars IS TABLE OF VARCHAR(1000) INDEX BY PLS_INTEGER;
gna_push_numbers gnt_push_numbers;
gva_push_varchars gvt_push_varchars;
FUNCTION PUSH ( pn_push_var NUMBER, pn_offset NUMBER) RETURN NUMBER DETERMINISTIC;
FUNCTION PUSH ( pv_push_var VARCHAR, pn_offset NUMBER) RETURN VARCHAR DETERMINISTIC;
FUNCTION POP_NUM ( pn_offset NUMBER) RETURN NUMBER DETERMINISTIC;
FUNCTION POP_VAR ( pn_offset NUMBER) RETURN VARCHAR DETERMINISTIC;
END stack;
CREATE OR REPLACE
PACKAGE BODY "STACK" AS
FUNCTION push(pn_push_var NUMBER, pn_offset NUMBER) RETURN NUMBER deterministic IS
BEGIN
gna_push_numbers(pn_offset) := pn_push_var;
RETURN pn_push_var;
END push;
FUNCTION push(pv_push_var VARCHAR, pn_offset NUMBER) RETURN VARCHAR deterministic IS
BEGIN
gva_push_varchars(pn_offset) := pv_push_var;
RETURN pv_push_var;
END push;
FUNCTION pop_num(pn_offset NUMBER) RETURN NUMBER deterministic IS
BEGIN
RETURN gna_push_numbers(pn_offset);
END pop_num;
FUNCTION pop_var(pn_offset NUMBER) RETURN VARCHAR deterministic IS
BEGIN
RETURN gva_push_varchars(pn_offset);
END pop_var;
END stack;
Unfortunately it appears to act before the rows are sorted, so will only work in specialised circumstances, in that you have to ensure the rows have been sorted before the function is used.
SELECT PUSH(COL), POP..(COL)
FROM ( SELECT etc.
Luckily the client decided they didn't want to mix their graphs any more so a more classic approach using a base table select for actuals and then a date table select with a sub-query columns for the projection provided a simple solution. -
How to do outer join select query for an APEX report
Hello everyone,
I am Ann.
I have one select statement that calculate the statistics for one month(October 2012 in this example)
select ph.phase_number
, sum ( (case
WHEN ph.date_finished IS NULL OR ph.date_finished > last_day(TO_DATE('Oct 2012','MON YYYY'))
THEN last_day(TO_DATE('Oct 2012','MON YYYY'))
ELSE ph.date_finished
END )
- ph.date_started + 1) / count(def.def_id) as avg_days
from phase_membership ph
inner join court_engagement ce on ph.mpm_eng_id = ce.engagement_id
inner join defendant def on ce.defendant_id = def.def_id
where def.active = 1
and ph.date_started <= last_day(TO_DATE('Oct 2012','MON YYYY'))
and ph.active = 1
and UPPER(ce.court_name) LIKE '%'
group by rollup(phase_number)
Result is as below
Phase_Number AVG_DAYS
Phase One 8.6666666666666667
Phase Two 14.6
Phase Three 12
11.4615365
I have other select list mainly list the months between two date value.
select to_char(which_month, 'MON YYYY') as display_month
from (
select add_months(to_date('Aug 2012','MON YYYY'), rownum-1) which_month
from all_objects
where
rownum <= months_between(to_date('Oct 2012','MON YYYY'), add_months(to_date('Aug 2012','MON YYYY'), -1))
order by which_month )
Query result is as below
DISPLAY_MONTH
AUG 2012
SEP 2012
OCT 2012
Is there any way that I can join these two select statement above to generate a result like:
Month Phase Number Avg days
Aug 2012 Phase One 8.666
Sep 2012 Phase One 7.66
Oct 2012 Phase One 5.66
Aug 2012 Phase Two 8.666
Sep 2012 Phase Two 7.66
Oct 2012 Phase Two 5.66
Aug 2012 Phase Three 8.666
Sep 2012 Phase Three 7.66
Oct 2012 Phase Three 5.66
Or
Month Phase Number Avg days
Aug 2012 Phase One 8.666
Aug 2012 Phase Two 7.66
Aug 2012 Phase Three 5.66
Sep 2012 Phase One 8.666
Sep 2012 Phase Two 7.66
Sep 2012 Phase Three 5.66
Oct 2012 Phase One 8.666
Oct 2012 Phase Two 7.66
Oct 2012 Phase Three 5.66
And it can be order by either Phase Number or Month.
My other colleague suggest I should use an left outer join but after trying so many ways, I am still stuck.
One of the select I tried is
select a.display_month,b.* from (
select to_char(which_month, 'MON YYYY') as display_month
from (
select add_months(to_date('Aug 2012','MON YYYY'), rownum-1) which_month
from all_objects
where
rownum <= months_between(to_date('Oct 2012','MON YYYY'), add_months(to_date('Aug 2012','MON YYYY'), -1))
order by which_month )) a left outer join
( select to_char(ph.date_finished,'MON YYYY') as join_month, ph.phase_number
, sum ( (case
WHEN ph.date_finished IS NULL OR ph.date_finished > last_day(TO_DATE(a.display_month,'MON YYYY'))
THEN last_day(TO_DATE(a.display_month,'MON YYYY'))
ELSE ph.date_finished
END )
- ph.date_started + 1) / count(def.def_id) as avg_days
from phase_membership ph
inner join court_engagement ce on ph.mpm_eng_id = ce.engagement_id
inner join defendant def on ce.defendant_id = def.def_id
where def.active = 1
and ph.date_started <= last_day(TO_DATE(a.display_month,'MON YYYY'))
and ph.active = 1
and UPPER(ce.court_name) LIKE '%'
group by to_char(ph.date_finished,'MON YYYY') , rollup(phase_number)) b
on a.display_month = b.join_month
but then I get an error
SQL Error: ORA-00904: "A"."DISPLAY_MONTH": invalid identifier
I need to display a report on APEX with option for people to download at least CSV format.
I already have 1 inteactive report in the page, so don’t think can add another interactive report without using the iframe trick.
If any of you have any ideas, please help.
Thanks a lot.
AnnFirst of all, a huge thanks for following this Frank.
I have just started working here, I think the Oracle version is 11g, but not sure.
To run Oracle APEX version 4, I think they must have at least 10g R2.
This report is a bit challenging for me.I has never worked with PARTITION before.
About the select query you suggested, I run , and it seems working fine, but if I try this,
it return error ORA-01843: not a valid month
DEFINE startmonth = "Aug 2012";
DEFINE endmonth = "Oct 2012";
WITH all_months AS
select add_months(to_date('&startmonth','MON YYYY'), rownum-1) AS which_month
, add_months(to_date('&startmonth','MON YYYY'), rownum ) AS next_month
from all_objects
where
rownum <= months_between(to_date('&endmonth','MON YYYY'), add_months(to_date('&startmonth','MON YYYY'), -1))
select TO_CHAR (am.which_month, 'Mon YYYY') AS month
, ph.phase_number
, sum ( (case
WHEN ph.date_finished IS NULL OR ph.date_finished > last_day(TO_DATE(am.which_month,'MON YYYY'))
THEN last_day(TO_DATE(am.which_month,'MON YYYY'))
ELSE ph.date_finished
END )
- ph.date_started + 1) / count(def.def_id) as avg_days
FROM all_months am
LEFT OUTER JOIN phase_membership ph PARTITION BY (ph.phase_number)
ON am.which_month <= ph.date_started
AND am.next_month > ph.date_started
AND ph.date_started <= last_day(TO_DATE(am.which_month,'MON YYYY')) -- May not be needed
AND ph.active = 1
LEFT OUTER join court_engagement ce on ph.mpm_eng_id = ce.engagement_id
and ce.court_name IS NOT NULL -- or something involving LIKE
LEFT OUTER join defendant def on ce.defendant_id = def.def_id
AND def.active = 1
group by rollup(phase_number, am.which_month)
ORDER BY am.which_month
, ph.phase_number
;Here is the shorted versions of the three tables:
A_DEFENDANT, A_ENGAGEMENT, A_PHASE_MEMBERSHIP
CREATE TABLE "A_DEFENDANT"
"DEF_ID" NUMBER NOT NULL ENABLE,
"FIRST_NAME" VARCHAR2(50 BYTE),
"SURNAME" VARCHAR2(20 BYTE) NOT NULL ENABLE,
"DOB" DATE NOT NULL ENABLE,
"ACTIVE" NUMBER(2,0) DEFAULT 1 NOT NULL ENABLE,
CONSTRAINT "A_DEFENDANT_PK" PRIMARY KEY ("DEF_ID"))
Sample Data
Insert into A_DEFENDANT (DEF_ID,FIRST_NAME,SURNAME,DOB,ACTIVE) values (101,'Joe','Bloggs',to_date('12/12/99','DD/MM/RR'),1);
Insert into A_DEFENDANT (DEF_ID,FIRST_NAME,SURNAME,DOB,ACTIVE) values (102,'John','Smith',to_date('20/05/00','DD/MM/RR'),1);
Insert into A_DEFENDANT (DEF_ID,FIRST_NAME,SURNAME,DOB,ACTIVE) values (103,'Jane','Black',to_date('15/02/98','DD/MM/RR'),1);
Insert into A_DEFENDANT (DEF_ID,FIRST_NAME,SURNAME,DOB,ACTIVE) values (104,'Minnie','Mouse',to_date('13/12/88','DD/MM/RR'),0);
Insert into A_DEFENDANT (DEF_ID,FIRST_NAME,SURNAME,DOB,ACTIVE) values (105,'Daisy','Duck',to_date('05/08/00','DD/MM/RR'),1);
CREATE TABLE "A_ENGAGEMENT"
"ENGAGEMENT_ID" NUMBER NOT NULL ENABLE,
"COURT_NAME" VARCHAR2(50 BYTE) NOT NULL ENABLE,
"DATE_REFERRED" DATE,
"DETERMINATION_HEARING_DATE" DATE,
"DATE_JOINED_COURT" DATE,
"DATE_TREATMENT_STARTED" DATE,
"DATE_TERMINATED" DATE,
"TERMINATION_TYPE" VARCHAR2(50 BYTE),
"ACTIVE" NUMBER(2,0) DEFAULT 1 NOT NULL ENABLE,
"DEFENDANT_ID" NUMBER,
CONSTRAINT "A_ENGAGEMENT_PK" PRIMARY KEY ("ENGAGEMENT_ID"))
Insert into A_ENGAGEMENT (ENGAGEMENT_ID,COURT_NAME,DATE_REFERRED,DETERMINATION_HEARING_DATE,DATE_JOINED_COURT,DATE_TREATMENT_STARTED,DATE_TERMINATED,TERMINATION_TYPE,ACTIVE,DEFENDANT_ID) values (1,'AA',to_date('12/08/12','DD/MM/RR'),null,to_date('12/08/12','DD/MM/RR'),null,null,null,1,101);
Insert into A_ENGAGEMENT (ENGAGEMENT_ID,COURT_NAME,DATE_REFERRED,DETERMINATION_HEARING_DATE,DATE_JOINED_COURT,DATE_TREATMENT_STARTED,DATE_TERMINATED,TERMINATION_TYPE,ACTIVE,DEFENDANT_ID) values (2,'BB',to_date('01/09/12','DD/MM/RR'),null,to_date('02/09/12','DD/MM/RR'),null,null,null,1,102);
Insert into A_ENGAGEMENT (ENGAGEMENT_ID,COURT_NAME,DATE_REFERRED,DETERMINATION_HEARING_DATE,DATE_JOINED_COURT,DATE_TREATMENT_STARTED,DATE_TERMINATED,TERMINATION_TYPE,ACTIVE,DEFENDANT_ID) values (3,'AA',to_date('02/09/12','DD/MM/RR'),null,to_date('15/09/12','DD/MM/RR'),null,null,null,1,103);
Insert into A_ENGAGEMENT (ENGAGEMENT_ID,COURT_NAME,DATE_REFERRED,DETERMINATION_HEARING_DATE,DATE_JOINED_COURT,DATE_TREATMENT_STARTED,DATE_TERMINATED,TERMINATION_TYPE,ACTIVE,DEFENDANT_ID) values (4,'BB',to_date('01/10/12','DD/MM/RR'),null,to_date('02/10/12','DD/MM/RR'),null,null,null,1,105);
CREATE TABLE "A_PHASE_MEMBERSHIP"
"MPM_ID" NUMBER NOT NULL ENABLE,
"MPM_ENG_ID" NUMBER NOT NULL ENABLE,
"PHASE_NUMBER" VARCHAR2(50 BYTE),
"DATE_STARTED" DATE NOT NULL ENABLE,
"DATE_FINISHED" DATE,
"NOTES" VARCHAR2(2000 BYTE),
"ACTIVE" NUMBER(2,0) DEFAULT 1 NOT NULL ENABLE,
CONSTRAINT "A_PHASE_MEMBERSHIP_PK" PRIMARY KEY ("MPM_ID"))
Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (1,1,'PHASE ONE',to_date('15/09/12','DD/MM/RR'),to_date('20/09/12','DD/MM/RR'),null,1);
Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (2,1,'PHASE TWO',to_date('21/09/12','DD/MM/RR'),to_date('29/09/12','DD/MM/RR'),null,1);
Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (3,2,'PHASE ONE',to_date('12/09/12','DD/MM/RR'),null,null,1);
Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (4,3,'PHASE ONE',to_date('20/09/12','DD/MM/RR'),to_date('01/10/12','DD/MM/RR'),null,1);
Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (5,3,'PHASE TWO',to_date('02/10/12','DD/MM/RR'),to_date('15/10/12','DD/MM/RR'),null,1);
Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (6,4,'PHASE ONE',to_date('03/10/12','DD/MM/RR'),to_date('10/10/12','DD/MM/RR'),null,1);
Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (7,3,'PHASE THREE',to_date('17/10/12','DD/MM/RR'),null,null,0);
Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (8,1,'PHASE THREE',to_date('30/09/12','DD/MM/RR'),to_date('16/10/12','DD/MM/RR'),null,1);
The requirements are:
The user must be able to request the extract for one or more calendar months, e.g.
May 2013
May 2013 – Sep 2013.
The file must contain a separate row for each calendar month in the requested range. Each row must contain the statistics computed for that calendar month.
The file must also include a row of totals.
The user must be able to request the extract for either Waitakere or Auckland or Consolidated (both courts’ statistics accumulated).
Then the part that I am stuck is
For each monitoring phase:
Phase name (e.g. “Phase One”)
Avg_time_in_phase_all_particip
for each phase name,
Add up days in each “phase name” Monitoring Phase, calculated as:
If Monitoring Phase.Date Finished is NULL or > month end date,
+(*Month end date* Minus Monitoring Phase.Date Started Plus 1)+
Otherwise (phase is complete)
+(Monitoring Phase.Date Finished Minus Monitoring Phase.Date Started Plus 1.)+
Divide by the numbers of all participants who have engaged in “phase name”.
This is the words of the Business Analyst,
I try to do as required but still struggle to identify end_month for the above formula to display for the range of months.
Of course, I can write two nested cursor. The first one run the list of month, then for each month, run the parameterised report.
But I prefer if possible just use SQL statements, or at least a PL/SQL but return a query.
With this way, I can create an APEX report, and use their CSV Extract function.
Yes, you are right, court_name is one of the selection parameters.
And the statistics is not exactly for one month. It is kind of trying to identify all phases that are running through the specified month (even phase.date_started is before the month start).
This is the reason why I put the condition AND ph.date_started <= last_day(TO_DATE('Oct 2012','MON YYYY')) (otherwise I get negative avg_days)
User can choose either one court "AA" or "BB" or combined which is all figures.
Sorry for bombarding you a lot of information.
Thanks a lot, again.
Edited by: Ann586341 on Oct 29, 2012 9:57 PM
Edited by: Ann586341 on Oct 29, 2012 9:59 PM -
Here is an Oracle 8i issue I've run into ....
I am trying to create a table that contains a record for each hour of the day (even if count is 0). I have a problem when I try a right outer join using the following syntax:
SELECT MDT.date_field, COUNT(*)
FROM MASTER_DATE_TABLE MDT, hsa_tgt.PICIS_OR POR
WHERE MDT.date_field = TO_CHAR(POR.OR_IN_DTTM,'YYYYMMDDHH24') (+)
AND TO_DATE(MDT.date_field,'YYYYMMDDHH24') >= '01-Jan-2006'
AND TO_DATE(MDT.date_field,'YYYYMMDDHH24') <= '31-Jan-2006'
GROUP BY MDT.date_field;
The problem 'SQL code no properly ended' only occurs if I use the TO_CHAR function (or any function for that matter) on the outer join line.
Is there a workaround? I did manage to create a temporary table and then successfully do an outer join in order to bypass having the to_char function in the join statement.
Maybe a union?
TIAI had to put it in a subquery? (if that's what it's called)
SELECT a1.date_field DateAndHour, b1.OR_date, NVL(b1.record_count,0)
FROM MASTER_DATE_TABLE a1,
(SELECT TO_CHAR(b.OR_IN_DTTM,'YYYYMMDDHH24') OR_date, COUNT(*) record_count
FROM hsa_tgt.PICIS_OR b
GROUP BY TO_CHAR(b.OR_IN_DTTM,'YYYYMMDDHH24')) b1
WHERE a1.date_field = b1.OR_date (+)
GROUP BY a1.date_field, b1.OR_date, b1.record_count
HAVING (TO_DATE(a1.date_field,'YYYYMMDDHH24') BETWEEN '01-Jan-2006' AND '31-Jan-2006')
ORDER BY a1.date_field; -
Hi
we are using oracle 8i, I am writing left outer join but i am getting error
AND to_char(A.SHORT_PROD_CD||A.PROD_MOD_CD) = ltrim('to_char(B.PFDR_PROD_CD)','0') (+)
and A.MFG_CO_CD=B.PFDR_MFG_CO_CD
These are the conditions. I know i am using left outer join on a SQL function thats why i am getting error. but my requirement to compare those values. bcz their are leading zeros what is the solution for this
SELECT A.PROD_ID,
NVL(B.MFFR_PROD_ID,(DECODE(MFG_CO_CD,3,-3,4,-4,8,-8,53,-53-1))) MFFR_PROD_ID,
NVL(B.MFFR_PROD_ID,(DECODE(MFG_CO_CD,3,-3,4,-4,8,-8,53,-53-1))) MFFR_RPTG_PROD_ID,
A.PROD_TYP_CD,
SYSDATE ROW_UPDT_UID_TMS,
SYSDATE ROW_UPDT_TMS,
NULL ROW_UPDT_UID_CD,
'SP_CROSS_REF_INSERT' ROW_UPDT_PGM_NO
FROM V_GET_SHORT_PROD_CD A,
MCCODS.MFFR_PROD B
WHERE A.PROD_TYP_CD = 'FG'
AND NVL(B.MFFR_PROD_RPTG_STAT_ID,999) <> 3
AND to_char(A.SHORT_PROD_CD||A.PROD_MOD_CD) = ltrim('to_char(B.PFDR_PROD_CD)','0') (+)
and A.MFG_CO_CD=B.PFDR_MFG_CO_CDSELECT a1.PROD_ID,
b1.MFFR_PROD_ID,
b1.MFFR_RPTG_PROD_ID,
a1.PROD_TYP_CD,
SYSDATE ROW_UPDT_UID_TMS,
SYSDATE ROW_UPDT_TMS,
NULL ROW_UPDT_UID_CD,
'SP_CROSS_REF_INSERT' ROW_UPDT_PGM_NO
FROM (Select A.PROD_ID,
A.PROD_TYP_CD,
to_char(A.SHORT_PROD_CD||A.PROD_MOD_CD) SHORT_MOD_CD,
A.MFG_CO_C
From V_GET_SHORT_PROD_CD A) a1,
(Select NVL(B.MFFR_PROD_ID,(DECODE(MFG_CO_CD,3,-3,4,-4,8,-8,53,-53-1))) MFFR_PROD_ID,
NVL(B.MFFR_PROD_ID,(DECODE(MFG_CO_CD,3,-3,4,-4,8,-8,53,-53-1))) MFFR_RPTG_PROD_ID,
NVL(B.MFFR_PROD_RPTG_STAT_ID,999) MFFR_PROD_RPTG_STAT_ID,
ltrim('to_char(B.PFDR_PROD_CD)','0') PFDR_PROD_CD,
B.PFDR_MFG_CO_CD
From MCCODS.MFFR_PROD B) b1
WHERE a1.PROD_TYP_CD = 'FG'
AND a1.SHORT_MOD_CD = b1.PFDR_PROD_CD (+)
and a1.MFG_CO_CD = b1.PFDR_MFG_CO_CD (+)
AND b1.MFFR_PROD_RPTG_STAT_ID(+) <> 3note: untested
Maybe you are looking for
-
Problema assinatura - Status 20 - Versão 006
Bom dia pessoALL, Já verifiquei os respectivos links abaixo e não consegui solucionar o meu problema : O cenário aqui é: ECC (NDE) 005A / ECC (NED) 006 < -- > GRC < -- > PI < -- > SEFAZ São dois ECC´s apontados para um ambiente GRC/PI. Estamos no SP
-
Problem with Image I/O and applet
I am having trouble using Image I/O to load a PNG image in an applet. I am just using a very basic applet that simply loads the image from a URL and that's it, and the exception I get is - java.lang.SecurityException: Unable to create temporary file
-
hi i buy macbook pro. how i can to connected with t.v hdmi? which cable television? tnx
-
I wish the export dialog calulated the file size based on the quality, type etc. EG: If im exporting a jpeg and slide the quality slider it would be cool to know what size of file i would get before exporting. Thanks, Braden
-
Multiple index.hmtl files
Can you tell me if I'm heading for trouble. I have created 2 sites which are linked through the Navigation menus. I've exported to a folder and now wish to upload them to a non .mac account. In the main folder named "AOS web" i have an index file the