Query on Join.
I have two tables...
in 1st table lets say emp_sal i have employees salary date wise.
for eg:
100 20 01-APR-2010
102 15 01-APR-2010
100 30 02-APR-2010
I need a query where i will give parameter From date and to_date it should return all emplyees sal and missing salary should return as 0
For eg... if is give 01-APR-10 as from date and 02-APR-10 as to date it should return
100 20 01-APR-2010
102 15 01-APR-2010
100 30 02-APR-2010
102 0 02-APR-2010
Pls help
Partitioned outer join would be perfect here:
with emp_sal as (select 100 empno, 20 salary, to_date('01/04/2010', 'dd/mm/yyyy') dt from dual union all
select 102 empno, 15 salary, to_date('01/04/2010', 'dd/mm/yyyy') dt from dual union all
select 100 empno, 30 salary, to_date('02/04/2010', 'dd/mm/yyyy') dt from dual),
-- end of mimicking your data in a subquery called emp_sal. Hurrah for subquery factoring!
dates as (select to_date('01/04/2010', 'dd/mm/yyyy') + level -1 dt -- replace the dates with your from_date/to_date parameters
from dual
connect by level <= to_date('02/04/2010', 'dd/mm/yyyy') - to_date('01/04/2010', 'dd/mm/yyyy') + 1)
select es.empno, nvl(es.salary, 0) salary, dates.dt
from dates
left outer join emp_sal es partition by (es.empno) on (dates.dt = es.dt);
EMPNO SALARY DT
100 20 01/04/2010
100 30 02/04/2010
102 15 01/04/2010
102 0 02/04/2010
Similar Messages
-
How to build a query to join on two tables without mapping
I did Automatic mapping by the workbench Directofield mapping with the table and java object.
Wanted to build a simple join query by joining on the same field on both the tables.Not the sql query through the toplink using expression builder.
Please help.............
Spent one full day for this................Thanks Don for the reply,sorry to bug you,but i need help.....
SELECT A.AGNCY_C,
A.TYPE_C,
A.RESN_C,
A.S_TYPE_C,
A.SUB_ID_C,
A.RY_C
FROM RATING A, REF B
WHERE A.ID_C = B._ID_C
AND A.ALPHA_C = B.ALPHA_C
AND A.EFF_D >= B.MATURITY_D
This is the real query i was talking about.I did mapping automatically through the workbench,generated java classes also throught the workbench.
Now they don't want to execute the raw sql.They wanted to get all the RATING objects with the where condition.
So how to build a query by using toplink.
tried your example
ExpressionBuilder builder = new ExpressionBuilder();
Expression creditRating = builder.getTable("RATING").getField("ID_C");
Expression issue_ref = builder.getTable("REF").getField("ID_C");
Expression join = creditRating.equal(issue_ref);
I am getting java.lang.OutOfMemoryError
error.
I selected the option generate classes and descriptors
from the tables (RATING,REF).,so it created the classes and dscriptors automatically.
In Database script for the table RATING like this
ALTER TABLE RATING ADD (
CONSTRAINT RATING_F1 FOREIGN KEY (ID_C, ALPHA_C)
REFERENCES REF (ID_C,ALPHA_C));
I think when i generate descriptor automatically it is keeping this association.
Please help me......... -
Query to join 2 tables by interval of value
Hi all
I need your help in creating a query to join 2 tables by interval of values.
The thing i want to d ois like this: i have 2 tables the first one containing list of serial number and the secon is containing interval of serial number (startnumber and end number) and other information like the user creating the serial number.
I want to list all serial numbers from the first table and the user creating each serial number from the second one if the serial number is between each interval of the second table.
here is an example>
SQL> create table test1 (code varchar2(1), serial number);
Table created.
SQL> create table test2 (requester varchar2(10),startno number, endno number);
Table created.
SQL> insert into test1 values('A',1);
1 row created.
SQL> insert into test1 values('B',3);
1 row created.
SQL> insert into test1 values('C',8);
1 row created.
SQL> insert into test1 values('D',12);
1 row created.
SQL> insert into test1 values('E',20);
1 row created.
SQL> commit;
Commit complete.
SQL> insert into test2 values('TATA',1,5);
1 row created.
SQL> insert into test2 values('TOTO',6,10);
1 row created.
SQL> commit;
Commit complete.
The result i want to get are:
TESt1.CODE TEST2.REQUESTER
A TATA
B TATA
C TOTO
D null
E nullUse outer join:
select code,
requester
from test1,
test2
where serial between startno(+) and endno(+)
order by code
C REQUESTER
A TATA
B TATA
C TOTO
D
E
SQL> SY. -
Need complex query with joins and AGGREGATE functions.
Hello Everyone ;
Good Morning to all ;
I have 3 tables with 2 lakhs record. I need to check query performance.. How CBO rewrites my query in materialized view ?
I want to make complex join with AGGREGATE FUNCTION.
my table details
SQL> select from tab;*
TNAME TABTYPE CLUSTERID
DEPT TABLE
PAYROLL TABLE
EMP TABLE
SQL> desc emp
Name
EID
ENAME
EDOB
EGENDER
EQUAL
EGRADUATION
EDESIGNATION
ELEVEL
EDOMAIN_ID
EMOB_NO
SQL> desc dept
Name
EID
DNAME
DMANAGER
DCONTACT_NO
DPROJ_NAME
SQL> desc payroll
Name
EID
PF_NO
SAL_ACC_NO
SALARY
BONUS
I want to make complex query with joins and AGGREGATE functions.
Dept names are : IT , ITES , Accounts , Mgmt , Hr
GRADUATIONS are : Engineering , Arts , Accounts , business_applications
I want to select records who are working in IT and ITES and graduation should be "Engineering"
salary > 20000 and < = 22800 and bonus > 1000 and <= 1999 with count for males and females Separately ;
Please help me to make a such complex query with joins ..
Thanks in advance ..
Edited by: 969352 on May 25, 2013 11:34 AM969352 wrote:
why do you avoid providing requested & NEEDED details?I do NOT understand what do you expect ?
My Goal is :
1. When executing my own query i need to check expalin plan.please proceed to do so
http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_9010.htm#SQLRF01601
2. IF i enable query rewrite option .. i want to check explain plan ( how optimizer rewrites my query ) ? please proceed to do so
http://docs.oracle.com/cd/E11882_01/server.112/e16638/ex_plan.htm#PFGRF009
3. My only aim is QUERY PERFORMANCE with QUERY REWRITE clause in materialized view.It is an admirable goal.
Best Wishes on your quest for performance improvements. -
SQL query -- self-join question?
SQL> l
1* select originator,destination,oaddress,daddress from (select * from activity where rownum<=3)
SQL> /
10099 10004 16196344392 16199375530
10064 10002 18454644069 18456563415
10065 10006 18302650166 16416609306
looking at the above query, i am just performing a simple select from one of my tables. Now i require the carriername for both originator and destination columns, and the names for these are found on another table carrier.
so, i am re-write the above query as: (join with carrier table)
SQL>
SQL> select originator,destination,oaddress,daddress,carriername from (select * from activity,carrier where originator=carrier_code and rownum<=3);
10006 10099 19182772772 19189553062 USA1
10004 10311 15096701636 15096692171 USA2
10000 10003 15125898141 15122930569 USA3
Now, i got the carrier name for my originator, how would i find the carriername for my destination also (in the same query). One way of doing it is joining the carrier table twice, but is there any other better approach.
Hope i am clear, any help will be greatly appreciated. Thanks.select
A.originator, A.destination, A.oaddress, A.daddress
, B.carrier_name name_originator
, C.carrier_name name_destination
from
activity A
,carrier B
,carrier C
where
A.originator = B.carrier_code
and A.destination = C.carrier_code -
Error in update query with join
hi all,
im using oracle 10g in windows.
im not able to use this update query having join......
UPDATE
b
SET
b.is_stud = 1
FROM
boy b
INNER JOIN
relationship r
ON
b.id = r.boy_id;
thanks a lot..................887268 wrote:
hi, thanks,,,,,,,,,
create table emp ( id,name,date,empno);
create table emp_status(slno,ename,empno);
i need to update "emp.name" in "emp" table from "emp_status.ename"
where emp.empno=emp_status.empno;
i.e) for all matched "empno" from both table, update "emp.name" from "emp_status.ename"Whats the relationship between emp and emp_status tables? If there exists one to one mapping for empno in both tables, then try
update emp e
set e.name = (select es.ename
from emp_status es
where e.empno = es.empno) -
query/right join/
Ultimately we are trying to find the ZZOMTAB.STAFF
I know the value exist because I have queried this by
K_NO
By this query
Select
ZZOMTAB.STAFF
from
ZZOMTAB
where
K_NO = 146735
so it is there
but what I am supplied with is app_no=79219
I have tried this query and it does not work ( no value in the ZZOMTAB.STAFF)
SELECT
ZZOMTAB.STAFF
FROM TKASERTAB
RIGHT JOIN ZZOMTAB
ON TKASERTAB.K_NO = ZZOMTAB.K_NO
RIGHT JOIN APPTAB
ON TKASERTAB.app_no= APPTAB.app_no
where
APPTAB.app_no=79219
the value that I am trying to get is in ZZOMTAB.STAFF
and I am given with app_no=79219
the tables are
tables are
TKASERTAB with columns K_NO and APPNO
APPTAB with column APPNO
and
ZZOMTAB with K_NO
I am trying to get the value of ZZOMTAB.STAFF
Can someone help??
Thanks in advquery/right join/
I have tried this query and it does not work ( no
value in the ZZOMTAB.STAFF)
SELECT
ZZOMTAB.STAFF
FROM TKASERTAB
RIGHT JOIN ZZOMTAB
ON TKASERTAB.K_NO = ZZOMTAB.K_NO
RIGHT JOIN APPTAB
ON TKASERTAB.app_no= APPTAB.app_no
where
APPTAB.app_no=79219
the value that I am trying to get is in
ZZOMTAB.STAFF
and I am given with app_no=79219
Why do You think, that the value must be here ?
Regards
Dmytro -
Write the following query using JOIN keyword ?
Qest:
Write the following query using JOIN keyword ?
select ID_category from category_master X
where Exist(select 1 from sub_category Y where
X.ID_category=Y.ID_category)Edited by: 799660 on Oct 3, 2010 6:05 AMselect X.ID_category
from category_master X join (select distinct ID_category from sub_category) Y
on (X.ID_category=Y.ID_category)
/SY. -
Hi,
Please give me the Select query
I have to fetch EBELN,BUKRS,LIFNR,BSART,EKORG,EKGRP,WAERS,WKURS from EKKO and
EBELP,LGORT,MATKL ,WERKS,BEDNR,IDNLF,BPRME,NETPR from EKPO and
MENGE, SAKTO,AUFNR,ANLN1,GSBER,PS_PSP_PNR from EKKN and
LPEIN,EINDT,SLFDT, from EKET.
I have to fetch all the data into an single internal table(Mandatory) by a select query using Joins.
EKKO is having EBELN as primary key
EKPO is having EBELN,EBELP as primary key
EKKN is having EBELN,EBELP as primary key
EKET is having EBELN,EBELP as primary key
Can anybody Please give me the Select query.
With Regards
AjayHi ,
I am sending this sample coed for the Inner joins .Hope this will help you:
Inner joins using 3 tables
Try this :-
SELECT stpostlnr stpoidnrk mastmatnr maramtart stpo~menge
INTO CORRESPONDING FIELDS OF TABLE zmat1 FROM mast
JOIN stpo ON stpostlnr = maststlnr
JOIN mara ON maramatnr = mastmatnr
WHERE stpostlty = 'M' "AND stpoidnrk IN s_matnr
AND mast~werks = 1000.
Here s_matnr is a select-options on the selection-screen.
Or this.
Code:
Select single VbrkBukrs VbrkKunrg Vbrk~Vbeln
VbrkFkdat VbrkBstnk_Vf Vbrk~Zterm
Tvzbt~Vtext
VbakVbeln VbakBstdk
LikpVbeln Likplfdat Likp~Lfuhr
into w_vbrk
from vbrk
inner join Tvzbt on TvzbtZterm = VbrkZterm and
Tvzbt~Spras = sy-langu
Inner join Vbfa as SalesLnk
on SalesLnk~vbeln = pu_vbeln and
SalesLnk~vbtyp_v = c_order
inner join Vbak on VbakVbeln = SalesLnkVbelv
Inner join Vbfa as DeliveryLnk
on DeliveryLnk~vbeln = pu_vbeln and
DeliveryLnk~vbtyp_v = c_Delivery
inner join Likp on LikpVbeln = DeliveryLnkVbelv
where vbrk~vbeln = pu_Vbeln.
This code locates sales, delivery and payment terms info from a billing document number.
or
Here, this one also works fine :
select zfpcdcadivi zfpcdproforma zfpcdfactura zfpcdaniofactura
zfpcdmontousd zfpcdmontoap zfpcdebeln zfpcdinco1
zfpcdlifnr lfa1name1 zcdvsstatus zfpcdconint
into it_lista
from zfpcd inner join zcdvs
on zfpcdebeln = zcdvsebeln
and zfpcdproforma = zcdvsproforma
and zfpcdlifnr = zcdvslifnr
inner join lfa1
on zfpcdlifnr = lfa1lifnr
where zcdvs~status = '04'.
Also Here is another solution that just uses inner joins:
SELECT vbakvbeln vbfaerdat INTO (itab-vbeln, itab-wadat)
FROM ( vbak INNER JOIN vbap
ON vbapvbeln = vbakvbeln )
INNER JOIN vbfa ON vbakvbeln = vbfavbelv
WHERE vbak~kunnr = m_wm AND
vbak~vbtyp = 'C' AND
vbfa~erdat IN s_date AND
vbap~matnr = 'MZ1807F' AND
vbfaposnv = vbapposnr AND
vbfa~vbtyp_n = 'J'.
<REMOVED BY MODERATOR>
Cheers,
Chandra Sekhar.
Edited by: Alvaro Tejada Galindo on Apr 10, 2008 5:20 PM -
Who to query and join nested elements
I have a table that contains a XMLTYPE Field. How do I query and join nested elements. For example I have a schema that has a PerstrenList element that holds one or more Perstren nodes. The Perstren node will contain a RemarksList node that can contain one or more Remarks nodes. My goal is to query all of the Remarks and join them with the information in it's parent node. Without the parent node information the remark is meaningless. Following is a example document and desire result set. I know how to query the Perstren or the Remarks I just can not figure out how to marry the two. The query should only return the remarks joined with the parent information.
<RasDataSet>
<PerstrenList>
<Perstren>
<TPERS>A</TPERS>
<DEPLY>B</DEPLY>
<STRUC>5</STRUC>
<RemarksList>
<REMARK>
<LABEL>ABC</LABEL>
<GENTEXT>Hello world</GENTEXT>
</REMARK>
<REMARK>
<LABEL>XYZ</LABEL>
<GENTEXT>Oracle XML</GENTEXT>
</REMARK>
<RemarksList>
</Perstren>
<Perstren>
<TPERS>C</TPERS>
<DEPLY>D</DEPLY>
<STRUC>4</STRUC>
<RemarksList>
<REMARK>
<LABEL>EFG</LABEL>
<GENTEXT>Database</GENTEXT>
</REMARK>
<RemarksList>
</Perstren>
<Perstren>
<TPERS>E</TPERS>
<DEPLY>F</DEPLY>
<STRUC>3</STRUC>
</Perstren>
<PerstrenList>
</RasDataSet>
desired Results
TPERS DEPLY LABEL GENTEXT
A B ABC Hello World
A B XYZ Oracle XML
C D EFG Database
select uic,
extractvalue(Column_value,'/Perstren/TPERS') as TPERS,
extractvalue(Column_value,'/Perstren/DEPLY') as DEPLY,
extractvalue(Column_value,'/Perstren/SECUR') as SECUR,
extractvalue(Column_value,'/Perstren/STRUC') as STRUC,
extractvalue(Column_value,'/Perstren/TIME') as TIME,
extractvalue(Column_value,'/Perstren/AUTH') as AUTH,
extractvalue(Column_value,'/Perstren/ASGD') as ASGD,
from test_ref doc,
table(XMLSequence(extract(doc.XML_DOC,'/RasDataSet/PerstrenList/Perstren'))) per
[pre]Sorry my Pre tag was in the wrong place Text reads:
I have a table that contains a XMLTYPE Field. How do I query and join nested elements. For example I have a schema that has a PerstrenList element that holds one or more Perstren nodes. The Perstren node will contain a RemarksList node that can contain one or more Remarks nodes. My goal is to query all of the Remarks and join them with the information in it's parent node. Without the parent node information the remark is meaningless. Following is a example document and desire result set. I know how to query the Perstren or the Remarks I just can not figure out how to marry the two. The query should only return the remarks joined with the parent information.
Sorry my Pre tag was in the wrong place -
Spatial query on join view in another schema
Background:
I have a schema with tables containing four spatial columns per table. I have a second schema that contains join views of the tables in the first schema. The join view consists of the attributes and any other tabular data that is joined via foreign key to non-spatial tables and one of the four geometry columns. I have a third schema that owns no database objects of its own, but has select privilege to the second schema's view objects.
We are using Oracle 10.2.0.2 on a windows platform.
This worked in 9i, the problem only presented itself when we migrated to 10g.
Problem:
When I run a spatial query on a join view in the second schema(the schema that owns the object), it runs and returns results in about a second. When I run the exact same query in the third schema it routinely takes 20-30 seconds.
Here is the query that I run in both schemas with varying query times:
SELECT COUNT(*)
FROM two.join_view_a A
WHERE (MDSYS.SDO_FILTER(A.GEOM, SDO_GEOMETRY(2003,8307,NULL,SDO_ELEM_INFO_ARRAY(1,1003,3),SDO_ORDINATE_ARRAY(26.6396,26.5708,43.346,34.4083)),'QUERYTYPE=WINDOW')='TRUE');
Question:
Why does this happen?
What can I do to fix this problem?
Thanks,
JohnHave a read of this posting: Oracle spatial view runing slow as different user
There are details there about the 'optimizer_secure_view_merging' parameter and the effect it can have on cross schema views in 10.2 -
Problem with a query inner-join
Hello;
I'm trying to innerjoin these 2 tables in my query for a page that will allow you to add / edit records. Right now, it's telling me I have a data mismatch. I don't see where I went wrong. Can someone help me out?
This is my code:
<cfparam name="url.CategoryID" type="integer" default="0">
<cfparam name="subID" type="integer" default="#url.CategoryID#">
<cfparam name="subName" default="">
<cfparam name="CategoryID" default="">
<cfparam name="Name" default="">
<cfif url.CategoryID GT 0>
<cfquery name="categRec" dataSource="#APPLICATION.dataSource#">
SELECT merchSubCat.subName, merchSubCat.subID, Categories.CategoryID, Categories.Name
FROM merchSubCat
INNER JOIN Categories
ON merchSubCat.CategoryID = Categories.CategoryID
WHERE merchSubCat.subID = <cfqueryparam value="#url.CategoryID#" cfsqltype="cf_sql_integer">
</cfquery>
<!--- if the record was found, store the values --->
<cfif categRec.RecordCount EQ 1>
<cfset CategoryID = categRec.subID>
<cfset subName = categRec.subName>
<cfset CategoryID = categRec.CategoryID>
<cfset Name = categRec.Name>
</cfif>
</cfif>
this is my error:
Error Executing Database Query.
[Macromedia][SequeLink JDBC Driver][ODBC Socket][Microsoft][ODBC Microsoft Access Driver] Type mismatch in expression.
The error occurred in C:\Websites\187914kg3\admin\cms\merchant\merchSub-edit.cfm: line 16
14 : INNER JOIN Categories
15 : ON merchSubCat.CategoryID = Categories.CategoryID
16 : WHERE merchSubCat.subID = <cfqueryparam value="#url.CategoryID#" cfsqltype="cf_sql_integer">
17 : </cfquery>
18 :
I don't see what I did wrong, can another pair of eyes see where I missed something?
Thank youI changed it to number, and it works now.
I have one other problem.. I'm trying to use a drop down menu in this form to edit a record. I want the drop down to show what is being used in the database when you go to edit a record. It runs on one query, to populate the select, but it pulls info from another and this isn't working. Actually, it's the innerjoin I just made.. can you help me?
<!--- query that runs the select --->
<cfquery name="catList" datasource="#APPLICATION.dataSource#">
SELECT DISTINCT merchCategory.CategoryID, merchCategory.CatName AS cat_name
FROM merchCategory
ORDER BY CatName
</cfquery>
<cfselect enabled="No" name="CategoryID" size="1" class="smallText" multiple="no" query="catList" value="CategoryID" display="cat_name" queryPosition="below" selected="#categRec.Name#">
<option value="">--Select a Category--</option>
</cfselect>
As you see, in the selected part of the tag, I'm trying to pull info from the other query we just fixed. I know this is wrong, how do I do this? -
Performance tuning in SQL query using join of views
Hi,
Am trying to tune a query of the format
select ........ from view1,view2
where view1.keyfield = view2.keyfield
The base tables of the views view1 and view2 have indexes specified on 'keyfield'.
However, when I do an explain plan of the query, Full table scan of those base tables are performed.
Even tried using Hints in this query to force Oracle to use those indexes, but still not successful.
Any pointers on how to tune this kind of query would be highly welcome.
Regards,
BaishIf your query is really of the same form as you posted, then full table scans then a hash or merge join may be the most efficient plan.
You are asking for all of the rows from view1 and the matching rows from view2, because of this, Oracle dedcided that the cost of full table scans using multi-block reads is cheaper than using single block reads to get the rowids from the index, then single block reads to get the rows from the table.
FULL SCAN <> BAD
John -
SAP Query to join action infotype with additional action infotype
We have created SAP Query on PA0000 which shows all actions that are executed for an employee.
The problem is that if two actions are exceuted on the same day then it shows only one action instead of showing both the actions.
As two actions are executed on the same day it will be stored in additional action infotype(0302).We tried to join PA0000(Action infotype) with PA0302(additional action infotype) in SAP Query by using joins(inner join/outer join) but it shows duplicate records.
Is there any way to get additional action along with records of action infotype without any duplication in SAP Query.All entries that are in PA0000 will be in PA0302, but not vice-versa so you just have to reverse what you are currently doing, i.e.: create a Query on PA0302 and join to PA0000, and then make sure your selection criteria is from PA0302 and not PA0000.
-
Need help in optimizing the query with joins and group by clause
I am having problem in executing the query below.. it is taking lot of time. To simplify, I have added the two tables FILE_STATUS = stores the file load details and COMM table that is actual business commission table showing records successfully processed and which records were transmitted to other system. Records with status = T is trasnmitted to other system and traansactions with P is pending.
CREATE TABLE FILE_STATUS
(FILE_ID VARCHAR2(14),
FILE_NAME VARCHAR2(20),
CARR_CD VARCHAR2(5),
TOT_REC NUMBER,
TOT_SUCC NUMBER);
CREATE TABLE COMM
(SRC_FILE_ID VARCHAR2(14),
REC_ID NUMBER,
STATUS CHAR(1));
INSERT INTO FILE_STATUS VALUES ('12345678', 'CM_LIBM.TXT', 'LIBM', 5, 4);
INSERT INTO FILE_STATUS VALUES ('12345679', 'CM_HIPNT.TXT', 'HIPNT', 4, 0);
INSERT INTO COMM VALUES ('12345678', 1, 'T');
INSERT INTO COMM VALUES ('12345678', 3, 'T');
INSERT INTO COMM VALUES ('12345678', 4, 'P');
INSERT INTO COMM VALUES ('12345678', 5, 'P');
COMMIT;Here is the query that I wrote to give me the details of the file that has been loaded into the system. It reads the file status and commission table to show file name, total records loaded, total records successfully loaded to the commission table and number of records that has been finally transmitted (status=T) to other systems.
SELECT
FS.CARR_CD
,FS.FILE_NAME
,FS.FILE_ID
,FS.TOT_REC
,FS.TOT_SUCC
,NVL(C.TOT_TRANS, 0) TOT_TRANS
FROM FILE_STATUS FS
LEFT JOIN
SELECT SRC_FILE_ID, COUNT(*) TOT_TRANS
FROM COMM
WHERE STATUS = 'T'
GROUP BY SRC_FILE_ID
) C ON C.SRC_FILE_ID = FS.FILE_ID
WHERE FILE_ID = '12345678';In production this query has more joins and is taking lot of time to process.. the main culprit for me is the join on COMM table to get the count of number of transactions transmitted. Please can you give me tips to optimize this query to get results faster? Do I need to remove group and use partition or something else. Please help!I get 2 rows if I use my query with your new criteria. Did you commit the record if you are using a second connection to query? Did you remove the criteria for file_id?
select carr_cd, file_name, file_id, tot_rec, tot_succ, tot_trans
from (select fs.carr_cd,
fs.file_name,
fs.file_id,
fs.tot_rec,
fs.tot_succ,
count(case
when c.status = 'T' then
1
else
null
end) over(partition by c.src_file_id) tot_trans,
row_number() over(partition by c.src_file_id order by null) rn
from file_status fs
left join comm c
on c.src_file_id = fs.file_id
where carr_cd = 'LIBM')
where rn = 1;
CARR_CD FILE_NAME FILE_ID TOT_REC TOT_SUCC TOT_TRANS
LIBM CM_LIBM.TXT 12345678 5 4 2
LIBM CM_LIBM.TXT 12345677 10 0 0Using RANK can potentially produce multiple rows to be returned though your data may prevent this. ROW_NUMBER will always prevent duplicates. The ordering of the analytical function is irrelevant in your query if you use ROW_NUMBER. You can remove the outermost query and inspect the data returned by the inner query;
select fs.carr_cd,
fs.file_name,
fs.file_id,
fs.tot_rec,
fs.tot_succ,
count(case
when c.status = 'T' then
1
else
null
end) over(partition by c.src_file_id) tot_trans,
row_number() over(partition by c.src_file_id order by null) rn
from file_status fs
left join comm c
on c.src_file_id = fs.file_id
where carr_cd = 'LIBM';
CARR_CD FILE_NAME FILE_ID TOT_REC TOT_SUCC TOT_TRANS RN
LIBM CM_LIBM.TXT 12345678 5 4 2 1
LIBM CM_LIBM.TXT 12345678 5 4 2 2
LIBM CM_LIBM.TXT 12345678 5 4 2 3
LIBM CM_LIBM.TXT 12345678 5 4 2 4
LIBM CM_LIBM.TXT 12345677 10 0 0 1 -
Query 4 joined tables with internal joins to represent a complex hierarchy!
I've got to refine/replace a query (Oracle 9i) that
currently joins rows from four tables in a hierarchical
fashion that I use to produce a listing like this:
agency abc 1
....division def 1.1
........service ghi 1.1.1
........service jkl 1.1.2
............faq mno 1.1.2.1
............faq pqr 1.1.2.2
........service stu 1.1.3
....division vwx 1.2
........service yyy 1.2.1
............faq zzz 1.2.1.1
The change involves allowing for unlimited levels of
nested child divisions to produce a listing like this:
agency abc 1
....division def 1.1
........service ghi 1.1.1
........service jkl 1.1.2
............faq mno 1.1.2.1
............faq pqr 1.1.2.2
........service stu 1.1.3
....division vwx 1.2
........division xxx 1.2.1
............division aaa 1.2.1.1
............division bbb 1.2.1.2
................service aaa 1.2.1.2.1
....................faq fff 1.2.1.2.1.1
....................faq ggg 1.2.1.2.1.2
........service yyy 1.2.1
............faq zzz 1.2.1.1
Notice the insertion of three nested divisions under
division 1.2 with services and faqs under those. The
order of names throughout is alphabetic within a nesting
level.
Here's the SQL I currently use, without nested divisions
(it contains extra info that I use to control what and
how names are displayed):
SELECT
agency.agency_id AGENCY_ID,
agency.agency_type_id AGENCY_TYPE_ID,
agency.name AGENCY_NAME,
agency.acronym AGENCY_ACRONYM,
agency.expiration_date AGENCY_EXP,
agency.post_count AGENCY_POST,
agency.stat AGENCY_STAT,
agency_type.agency_type AGENCY_TYPE,
division.division_id DIV_ID,
division.name DIV_NAME,
division.transfer_number DIV_TRANS_NUM,
division.expiration_date DIV_EXP,
division.post_count DIV_POST,
division.stat DIV_STAT,
service.service_id SVC_ID,
service.name SVC_NAME,
service.taxonomy SVC_TAX,
service.keywords SVC_KEYWORDS,
service.action_type SVC_ACTION_TYPE,
service.sr_form_name SVC_SR_FORM,
service.expiration_date SVC_EXP,
service.post_count SVC_POST,
service.stat SVC_STAT,
faq.faq_id FAQ_ID,
faq.name FAQ_NAME,
faq.expiration_date FAQ_EXP,
faq.post_count FAQ_POST,
faq.stat FAQ_STAT
FROM
agency,
agency_type,
division left join service on
division.division_id=service.division_id left join
faq on service.service_id=faq.service_id
WHERE (
(agency_type.agency_type_id = agency.agency_type_id)
AND (agency.agency_id = division.agency_id)
AND (agency.agency_id = :agency_id )
It's very fast -- I can retrieve and display 5,000 rows
in seconds using Perl DBI and CGI -- and very easy to use
to produce the hierarchical listing of items from the
four tables. It is also very straightforward since I was
able to generate the SQL using the SQL modeler in TOAD
(I'm not the strongest SQL developer so I resort to
tools).
I need to get jump-started in the right direction to
determine what I need to add to my division table
(div_parent_id?), if I need a div_parent_child table to
define the relationships (rows with parent_id & child_id
pairs), and how to change or rewrite the SQL query. The
CGI form that will be used to define the relationships
will ask users to define children of a given division. I
envision presenting a list of divisions with null
parent_division_id columns for users to select from then
updating selected rows for selected divsions.
Thanks in advance for any help/guidance!
-GeneINLINE VIEWS!
select whatever_you_want
from (
SELECT FOLDER_ID, PARENT_FOLDER_ID, FOLDER_NAME
FROM FOLDERS
START WITH PARENT_FOLDER_ID = 0 CONNECT BY PARENT_FOLDER_ID = PRIOR FOLDER_ID
) tree, FILES
where tree.folder_id = files.folder_id -- or something like that
always try to keep the CONNECT BY limited to ONE AND ONLY table. then use that query in a subquery, a WITH clause, an inline view or something. do not try to JOIN or UNION with a CONNECT BY. it won't work the way you think it will, and even it returns the expected results, it will perform terribly.
* your mileage may vary
Message was edited by:
shoblock
added exclamation marks to show my excitement!!!!
Maybe you are looking for
-
Can I Edit SD and HDV footage at the same time in CS4?
I have a Sony PD 150 camcorder and I'm looking at buying a Sony HDR-HC# HDV 1080i camcorder to use as a second camera on video shoots. Can I edit footage from both cameras on the same timeline in CS4? I'm using a PC, running Windows XP Home Editi
-
Suddenly strange French characters appearing instead of what the keyboard shows
I have a brand new HP Touchless 520-1050 with a wireless keyboard. I have the language set to Canadian English (and I double checked that by checking via the control panel). There is a button on the keyboard (2nd from the left bottom row) that says
-
Error Code 0x8002006E (Every CD burn attempt ends in failure)
Hey guys, Title of the thread kinda says it all. Everytime I burn a disc, I get an error maybe 75% of the way in. It doesn't matter if I'm burning with Toast or just using OSX Finder to do it. Anyhow, I was wondering if anyone knew what was up before
-
Business Process in Chemical Industry.
Hi, I want to gain domain knowledge in Chemical Industry.So,please suggest from where should I start and how to get complete business knowledge in Chemical industry. Thanks & Regards, Divya.
-
X-fi card and Home theater Speakers can I get Game sounds EAX e
Ok after spending hours on this forum and realizing that I just spend $200 on a card to hook up my computer to my home theater to play games on my 37 LCD I find out that I can not get any of the sound card gaming features while using my $50 optical c