Left Join query help
select * from ort
bid mid
18083 7
select * from st
tid bid mid act
318 18083 5 20091
318 18083 6 20091
321 18083 7 NULL
318 18083 16 23970
my out put should be
318 18083 6 20091
(basic idea is
In order to do this I wrote the following query. But I am getting the following error ora-01799. How do i fix this?
select ort.bid,st.tid from ort
left join st
on ort.BiD = st.bid
and st.mid in
(select max(MID)
from St
where BID = ort.BID and TID is not null and MID <= ort.MID
and ACT is not null
)
May be this will clear up what I am trying to acheive a little better. I truly appreciate all your help. I have enclosed column headings and data items within double quotes and data is enclosd in double-quotes and separated by comma.
SQL> desc ort
"Name" "Null?" "Type"
"BID" "NUMBER"
"MID" "NUMBER"
SQL> desc st
"Name" "Null?" "Type"
"TID" "NUMBER"
"BID" "NUMBER"
"MID" "NUMBER"
"ACT" "NUMBER"
"LTP" "NUMBER(10)"
SQL> select * from ort
2 ;
"BID" "MID"
"18083", "7"
"18083", "6"
"18083", "16"
"18083", "277"
"18083", "117"
SQL> select * from st;
"TID" "BID" "MID" "ACT" "LTP"
"NULL", "18083", "117", "NULL", "246"
"NULL", "18083", "277", "NULL", "246"
"246", "18083", "272", "54998", "246"
"318", "18083", "6", "20091" "NULL"
"321", "18083", "7", "NULL", "NULL"
"318", "18083", "16", "23970", "NULL"
6 rows selected.
SQL> SELECT ort.bid, st.tid, st.mid, st.act
2 FROM ort
3 LEFT OUTER JOIN
4 st
5 ON ort.bid = st.bid
6 AND st.mid IN (SELECT mid
7 FROM myortview);
"BID" "TID" "MID" "ACT"
"18083", "246", "272", "54998"
"18083", "246", "272", "54998"
"18083", "246", "272", "54998"
"18083", "246", "272", "54998"
"18083", "246", "272", "54998"
SQL> -- expected result is
bid tpid ort.mid st. mid
"18083", "246", "277", "272"
"18083", "246", "117", "116"
"18083", "318", "16", "16"
"18083", "318", "6", "6"
"18083", "318", "7", "6"
Similar Messages
-
Hi Everyone,
Can someone pls shed some light on the situation below
I am understanding alot of what Michael and Rod wrote.... with my prev. post of LEFT JOIN and testing for
not null and doing a double Boolean OR etc.
- but- AM NOT understanding why the IS NOT NULL works, without the double boolean OR
Pls help... have to explain what left join means to user tomm. I'm going to demo the query below and
not the one with the double boolean OR bec. maybe too much info to present at one sitting. tx, sandra
=====================
the query below is left joining the STUDENT table to
HOLD table.
The HOLD table - contains rows for students who have holds on their record.
a student can have more than one hold (health, HIPAA, basic life saving course)
BUT, for this query: I'm only interested that a hold exists, so I'm choosing MAX on hold desc.
Selecting a MAX, helps me, bec. it reduces my join to a 1 to 1 relationship, instead of
1 to many relationship.
Before I posted this thread at all, the LEFT JOIN below testing for IS NOT NULL worked w/o
me having to code IS NOT NULL twice....
Is that because, what's happening "behind the scenes" is that a temporary table containing all max rows is being
created, for which Discoverer has no predefined join instructions, so it's letting me do a LEFT JOIN and have
the IS NOT NULL condition.
I would so appreciate clarification. I have a meeting on Tues, for which I have to explain LEFT JOINS to the user
and how they should create a query. I need to come up with rules.
If I feel "clear", I asked my boss to buy Camtasia videocast software to create a training clip for user to follow.
Also, if any Banner user would like me to email the DIS query to run on their machine, I would be glad to do so.
thx sooo much, Sandra
SELECT O100384.ACADEMIC_PERIOD, O100255.ID, O100384.ID, O100255.NAME, O100384.NAME, O100255.PERSON_UID, O100384.PERSON_UID, MAX(O100255.HOLD_DESC)
FROM ODSMGR.HOLD O100255, ODSMGR.STUDENT O100384
WHERE ( ( O100384.PERSON_UID = O100255.PERSON_UID(+) ) ) AND ( O100384.ACADEMIC_PERIOD = '200820' )
GROUP BY O100384.ACADEMIC_PERIOD, O100255.ID, O100384.ID, O100255.NAME, O100384.NAME, O100255.PERSON_UID, O100384.PERSON_UID
HAVING ( ( MAX(O100255.HOLD_DESC(+)) ) IS NOT NULL )
ORDER BY O100384.NAME ASCHi,
OK, I will try to explain this. When you outer join table B to table A then the rows in table A which do not match any rows in table B will returned with NULL in the columns from the table B.
Oracle uses the syntax ( +) for outer joins. Now if you add another condition using the ( +) syntax (as shown below) the condition will be processed before the table is joined. Therefore if table A does not match any rows in table B which have col2=1 then the row from table A will be returned with NULLs for the table B columns.
SELECT A.col1, B.col1
FROM A, B
WHERE A.col1 = B.col1( +)
AND B.col2( +)=1
Now, if the condition B.col2=1 was used instead then the condition would be processed after the join and therefore the rows from table A that were joined to table B but did not meet the condition would not be returned by the query.
This applies to a WHERE clause and to the HAVING clause, but with one exception. If you use the ( +) within a group function in a HAVING clause then the ( +) will have no affect because the condition must be processed after group by and group by can only be processed after the join. Therefore MAX(B.col2( +)) = 1 is processed after the join even through it uses the ( +) syntax.
You cannot use an OR or an IN with the ( +) syntax because the meaning of the OR in this situation is ambiguous, is the OR done before or after the join. A query with an OR or IN in an outer will fail with an Oracle ORA-01719 error. Discoverer recognises this situation and removes the ( +) so that the error does not occur. However, without the ( +) the conditions are processed after the join.
Using the ( +) with IS NULL, e.g. col2( +) IS NOT NULL works in the same way. You just have to remember that the col2( +) could be NULL as a result of the outer join and therefore if the condition is processed after the query then the IS NOT NULL will remove the outer joined rows.
Hope that is clear.
Rod West -
Hi,
I have one ejbql for selecting records from one table which are not in the other table.There is actually records in the data base but by using this query it is retrieving noting . The corresponding pl/sql query is working fine and it is retrieve correct result .what is wrong with my query.. Plz help me to correct this query...
My ejbql is below...
EJB-QL
SELECT C.name FROM person C LEFT JOIN C.address FC WHERE C.id.name= FC.id.name AND FC.id.pcode IS NULL
There is no result while executing this query. The correspoinding pl sql query is
PL/SQL
SELECT e_person .* FROM e_person ep LEFT JOIN e_address ea ON ep .name= ea .name WHERE ea.pcode IS NULL
plz help ...
Thanks in advance
AniEnable logging and include the SQL generated for the JPQL.
JPQL will also join via the primary/foreign key define in the mapping when you do C.address, if this is not name then you may be joining by something else. You could just declare the Address independent of the Employee if you do not wish to join by primary key (although this seems odd).
-- James : http://www.eclipselink.org -
hi
i am encountering error like the values not getting populated in internal table though values are in dbtable...so if u can help me out in the join query it will be of gr8 help
SELECT a1~guid a1~posting_date a1~process_type
b1~sales_org b1~division b1~dis_channel
INTO CORRESPONDING FIELDS OF TABLE it_ordel
FROM ( ( crmd_orderadm_h AS a1 INNER JOIN crmd_link AS c1 ON a1~guid = c1~guid_hi )
INNER JOIN crmd_orgman AS b1 ON c1~guid_hi = b1~guid )
WHERE c1~objtype_hi = '05'
AND c1~objtype_set = '21'.
AND a1~process_type IN so_prst
AND a1~posting_date IN so_podt
AND b1~division IN so_div.
thnxSELECT a1~guid a1~posting_date a1~process_type
b1~sales_org b1~division b1~dis_channel
INTO CORRESPONDING FIELDS OF TABLE it_ordel
FROM ( ( crmd_orderadm_h AS a1 INNER JOIN crmd_link AS c1 ON a1~guid = c1~guid_hi )
INNER JOIN crmd_orgman AS b1 ON c1~guid_hi = b1~guid )
WHERE c1~objtype_hi = '05'
AND c1~objtype_set = '21'.
AND a1~process_type IN so_prst
AND a1~posting_date IN so_podt
AND b1~division IN so_div.
SELECT a1~guid a1~posting_date a1~process_type
b1~sales_org b1~division b1~dis_channel
INTO CORRESPONDING FIELDS OF TABLE it_ordel
FROM ( ( crmd_orderadm_h AS a1 INNER JOIN crmd_link AS c1 ON a1~guid = c1~guid_hi )
INNER JOIN crmd_orgman AS b1 ON c1~guid_hi = b1~guid )
WHERE c1~objtype_hi = '05'
AND c1~objtype_set = '21' ". delete that period its wrong
AND a1~process_type IN so_prst
AND a1~posting_date IN so_podt
AND b1~division IN so_div. -
Don'T repeat item with a LEFT JOIN QUERY
Hello,
I would like to know how display the following results:
*Name*: John Fox
*Sales:* 1- LAPTOP
2- HARDDRIVE
3- COMPUTERHere is my 2 tables: CUSTOMER and SALES
CUSTOMER
ID NAME GENDER
1 John Mayer F
2 Melissa John F
3 Julie Black F
4 Mickael Fox M
5 John Fox M
SALES
ID ID_CUSTOMER TYPE
1 1 Boat
2 1 TV
3 4 CD PLAYER
4 5 LAPTOP
5 5 HARDDRIVE
6 5 COMPUTER
My QUERY
SELECT customer.Name as NAME, customer.Gender, sales.TYPE
from customer
LEFT JOIN sales
ON customer.ID = sales.ID_CUSTOMER
WHERE customer.Name = 'John Fox'The problem: If I use the default template, I have:
NAME GENDER TYPE
John Fox M LAPTOP
John Fox M HARDDRIVE
John Fox M COMPUTER I don'T want the Name John Fox to be repeated at each row.
I tried to add: #Name# in the REGION DEFINITION - REGION HEADER but I have this result:
#NAME#
NAME GENDER TYPE
John Fox M LAPTOP
John Fox M HARDDRIVE
John Fox M COMPUTER
So, what can I do to have this result? Change the query???
Name: John Fox
Sales: 1- LAPTOP
2- HARDDRIVE
3- COMPUTER thanks,
RoselineHi Roseline,
You can adapt the solution suggested in this post Re: More than 1 records in one cell
Thanks,
Manish -
I am tuning a SELECT query with 36 Left Joins in addition to normal Inner Joins and a View.
I have used the RESULT_CACHE hint with some success.
I have tried the LEADING hint and USE_MERGE with no success.
Is there an Undocumented HINT and that may assist me?
Thanks
BRADHi, Brad,
Welcome to the forum!
970109 wrote:
I am tuning a SELECT query with 36 Left Joins in addition to normal Inner Joins and a View.Why does the query need so many outer joins? Could there be a bad table design behind this problem? Post a simplified version ot the problem (with maybe 3 tables that need to be outer-joined). Post CREATE TABLE and INSERT statements for a little sample data (relevant columns only), the results you want from that sample data, and an explanation of how you get those results from that data.
See the forum FAQ {message:id=9360002}
For all tuning problems, see {message:id=9360003} -
Left join query with join of three tables
I'm trying to build a query which has me stumped. Most of the query is fairly straightforward but I've run into an issue I'm not sure how to solve.
Background:
We have actions stored in i_action.
We have the available attributes for each type of action. The available attributes for each action are described in shared_action_attribute. Each type of action may have up to three attributes or none at all.
We have the values stored for the attributes in i_attribute_value.
A written example:
We have a transfer action (action_code B4). The entry of the B4 action into i_action records the fact that the transfer occurred and the date on which it occurred. The available attributes for a transfer action are the receiving function code, the receiving unit number, and the transfer reason code. These available attribute types and their order are stored in shared_action_attribute. The actual values of the attributes for a specific transfer action are stored in i_attribute_value.
Now i_action and i_attribute_value can be directly linked through action_seq in i_action and ia_action_seq in i_attribute_value. A left join built between these two tables provides results for all actions (including actions which have no attributes) and attribute values (see query 1 below).
There are two issues. First, I only want the first two attributes. In order to specify the first two attributes, I also have to link i_attribute_value to shared_action_attribute (which is where the order is stored). I can build a simple query (without the left join) linking the three tables but then actions with no attributes would be excluded from my result set (see query 2 below).
The second issue is that I would actually like one row returned for each action with first_attribute and second_attribute as columns instead of two rows.
The final query will be used to create a materialized view.
Here are the tables and examples of what's stored in them:
TABLE i_action
Name Type
ACTION_SEQ NUMBER(10)
ACTION_DATE DATE
ACTION_CODE VARCHAR2(3)
DELETED VARCHAR2(1)
EXAMPLE ROWS
ACTION_SEQ ACTION_DATE ACTION_CODE DELETED
45765668 09-OCT-09 B2 A
45765670 09-OCT-09 BA A
45765672 09-OCT-09 B6 A
45765673 09-OCT-09 B4 A
45765674 09-OCT-09 G1 A
45765675 09-OCT-09 M3 A
TABLE i_attribute_value
Name Type
IA_ACTION_SEQ NUMBER(10)
SACTATT_SACT_CODE VARCHAR2(3)
SACTATT_SAT_TYPE VARCHAR2(3)
VALUE VARCHAR2(50)
EXAMPLE ROWS
IA_ACTION_SEQ SACTATT_SACT_CODE SACTATT_SAT_TYPE VALUE
45765668 B2 ACO 37B
45765670 BA ROA D
45765670 BA ROR P
45765672 B6 CAT C
45765673 B4 RFC E
45765673 B4 TRC P
45765673 B4 RUN 7
45765674 G1 SS 23567
45765674 G1 ASG W
TABLE shared_action_attribute
Name Type
SACT_CODE VARCHAR2(3)
SAT_TYPE VARCHAR2(3)
ORDER NUMBER(2)
TITLE VARCHAR2(60)
EXAMPLE ROWS
SACT_CODE SAT_TYPE ORDER TITLE
B2 ACO 1 Office code
BA ROR 1 Reason for reopen
BA ROA 2 Reopen authority
B6 CAT 1 Category
B4 RFC 1 Receiving function code
B4 RUN 2 Receiving unit code
B4 TRC 3 Transfer reason code
G1 SS 1 Staff sequence
G1 ASG 2 Assignment reason
QUERY 1:
This is my current query along with its results. Most of it is straightforward select but one column is populated using the last_value analytical function (thanks to you guys). The last column in the below view stores the attribute value. What I want is to replace that single column with two columns named first_attribute and second_attribute and to eliminate any other attributes.
SELECT ia.action_seq, ia.action_date, ia.action_code cod,
NVL
(LAST_VALUE (CASE
WHEN ia.action_code = 'G1'
AND iav.sactatt_sat_type = 'SS'
THEN VALUE
WHEN ia.action_code IN ('A0', 'A1')
THEN '67089'
END IGNORE NULLS
) OVER (PARTITION BY ia.ici_charge_inquiry_seq ORDER BY ia.action_date,
ia.serial_number, ia.action_seq),
'67089'
) staff_seq,
value
FROM i_action ia LEFT JOIN i_attribute_value iav
ON iav.ia_action_seq = ia.action_seq
WHERE ia.deleted = 'A';
ACTION_SEQ ACTION_DA COD STAFF_SEQ VALUE
45765668 09-OCT-09 B2 67089 37B
45765670 09-OCT-09 BA 67089 D
45765670 09-OCT-09 BA 67089 P
45765672 09-OCT-09 B6 67089 C
45765673 09-OCT-09 B4 67089 E
45765673 09-OCT-09 B4 67089 P
45765673 09-OCT-09 B4 67089 7
45765674 09-OCT-09 G1 23567 23567
45765674 09-OCT-09 G1 23567 W
45765675 09-OCT-09 M3 23567
QUERY 2:
This query limits to the first two attributes but it also drops actions which have no attributes and it still creates multiple rows for each action instead of a single row with two columns for the attributes.
SELECT ia.action_seq, ia.action_date, ia.action_code cod,
NVL
(LAST_VALUE (CASE
WHEN ia.action_code = 'G1'
AND iav.sactatt_sat_type = 'SS'
THEN VALUE
WHEN ia.action_code IN ('A0', 'A1')
THEN '67089'
END IGNORE NULLS
) OVER (PARTITION BY ia.ici_charge_inquiry_seq ORDER BY ia.action_date,
ia.serial_number, ia.action_seq),
'67089'
) staff_seq,
value
FROM shared_action_attribute saa, ims_action ia, ims_attribute_value iav
WHERE iav.ia_action_seq = ia.action_seq
AND iav.sactatt_sact_code = saa.sact_code
AND iav.sactatt_sat_type = saa.sat_type
AND saa.display_order IN ('1','2')
AND ia.deleted = 'A';
ACTION_SEQ ACTION_DA COD VALUE
45765668 09-OCT-09 B2 67089 37B
45765670 09-OCT-09 BA 67089 D
45765670 09-OCT-09 BA 67089 P
45765672 09-OCT-09 B6 67089 C
45765673 09-OCT-09 B4 67089 E
45765673 09-OCT-09 B4 67089 7
45765674 09-OCT-09 G1 23567 23567
45765674 09-OCT-09 G1 23567 W
I found this pretty complex to try to write out - I hope I've been clear.
Thanks so much!Ok, here's more information with a simplified question. I figured out the syntax for building my query with the three tables. My final query returns multiple rows (multiple attributes per action). Instead of multiple rows, I'd like two columns (first_attribute, and second_attribute) in a single row (I only need the first two attributes).
Here's the action table:
CREATE TABLE I_ACTION
ACTION_SEQ NUMBER(10) NOT NULL,
ACTION_DATE DATE,
ACTION_CODE VARCHAR2(3 BYTE) NOT NULL,
DELETED VARCHAR2(1 BYTE),
);With the following rows added:
Insert into I_ACTION (ACTION_SEQ, ACTION_DATE, ACTION_CODE, DELETED)
Values (45765668, '09-oct-2009', 'B2', 'A');
Insert into I_ACTION (ACTION_SEQ, ACTION_DATE, ACTION_CODE, DELETED)
Values (45765670, '09-oct-2009', 'BA', 'A');
Insert into I_ACTION (ACTION_SEQ, ACTION_DATE, ACTION_CODE, DELETED)
Values (45765672, '09-oct-2009', 'B6', 'A');
Insert into I_ACTION (ACTION_SEQ, ACTION_DATE, ACTION_CODE, DELETED)
Values (45765673, '09-oct-2009', 'B4', 'A');
Insert into I_ACTION (ACTION_SEQ, ACTION_DATE, ACTION_CODE, DELETED)
Values (45765674, '09-oct-2009', 'G1', 'A');
Insert into I_ACTION (ACTION_SEQ, ACTION_DATE, ACTION_CODE, DELETED)
Values (45765675, '09-oct-2009', 'M3', 'A');
COMMIT;The attribute table is:
CREATE TABLE I_ATTRIBUTE_VALUE
IA_ACTION_SEQ NUMBER(10) NOT NULL,
SACTATT_SACT_CODE VARCHAR2(3 BYTE) NOT NULL,
SACTATT_SAT_TYPE VARCHAR2(3 BYTE) NOT NULL,
VALUE VARCHAR2(50 BYTE),
);With the following rows:
Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
Values (45765668, 'B2', 'ACO', '37B');
Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
Values (45765670, 'BA', 'ROR', 'P');
Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
Values (45765670, 'BA', 'ROA', 'D');
Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
Values (45765672, 'B6', 'CAT', 'C');
Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
Values (45765673, 'B4', 'RFC', 'E');
Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
Values (45765673, 'B4', 'RUN', '7');
Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
Values (45765673, 'B4', 'TRC', 'P');
Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
Values (45765674, 'G1', 'SS', '23567');
Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
Values (45765674, 'G1', 'ASG', 'W');
COMMIT;And finally, the shared table:
CREATE TABLE SHARED_ACTION_ATTRIBUTE
SACT_CODE VARCHAR2(3 BYTE) NOT NULL,
SAT_TYPE VARCHAR2(3 BYTE) NOT NULL,
TITLE VARCHAR2(25 BYTE) NOT NULL,
DISPLAY_ORDER NUMBER(2) NOT NULL
);With the following rows:
Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
Values ('B4', 'RFC', 'Y', 'Rcv. Function Code', 1);
Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
Values ('B6', 'CAT', 'Y', 'Category', 1);
Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
Values ('G1', 'SS', 'Y', 'Staff Name', 1);
Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
Values ('B2', 'ACO', 'Y', '"Other" Office Code', 1);
Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
Values ('B4', 'RUN', 'Y', 'Receiving Unit Number', 2);
Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
Values ('B6', 'LEP', 'N', 'LEP Issue/Sub Category', 2);
Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
Values ('B4', 'TRC', 'Y', 'Transfer Reason Code', 3);
Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
Values ('B6', 'NEP', 'N', 'NEP Issue', 3);
Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
Values ('G1', 'ASG', 'Y', 'Assignment Reason', 2);
Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
Values ('B2', 'MSN', 'S', 'Machine Serial Number', 3);
Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
Values ('BA', 'ROR', 'Y', 'Reopen Reason', 1);
Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
Values ('BA', 'ROA', 'Y', 'Reopen Authority', 2);
COMMIT;Now, this is my current query (it's changed from my first post):
SELECT ia.action_seq, ia.ici_charge_inquiry_seq, ia.action_date,
ia.serial_number, ia.reporting_office, ia.reporting_function,
ia.reporting_unit, ia.action_code, ia.machine_serial_number,
NVL
(LAST_VALUE (CASE
WHEN ia.action_code = 'G1'
THEN VALUE
WHEN ia.action_code IN ('A0', 'A1')
THEN '67089'
END IGNORE NULLS
) OVER (PARTITION BY ia.ici_charge_inquiry_seq ORDER BY ia.action_date,
ia.serial_number, ia.action_seq),
'67089'
) staff_seq,
(CASE
WHEN display_order = '1'
THEN VALUE
END) first_attribute,
(CASE
WHEN display_order = '2'
THEN VALUE
END) second_attribute
FROM ims_action ia
LEFT JOIN ims_attribute_value iav
ON iav.ia_action_seq = ia.action_seq
LEFT JOIN shared_action_attribute
ON sactatt_sact_code = sact_code
AND sactatt_sat_type = sat_type
WHERE ia.deleted = 'A';Which gives me the following results:
ACTION_SEQ ACTION_DA ACT STAFF_SEQ FIRST_ATTRIBUTE SECOND_ATTRIBUTE
45765668 09-OCT-09 B2 67089 37B
45765670 09-OCT-09 BA 67089 D
45765670 09-OCT-09 BA 67089 P
45765672 09-OCT-09 B6 67089 C
45765673 09-OCT-09 B4 67089 E
45765673 09-OCT-09 B4 67089 7
45765673 09-OCT-09 B4 67089
45765674 09-OCT-09 G1 23567 W
45765674 09-OCT-09 G1 23567 23567
45765675 09-OCT-09 M3 23567 The result I WANT is similar but I want the two separate attribute columns on one row as such:
ACTION_SEQ ACTION_DA ACT STAFF_SEQ FIRST_ATTRIBUTE SECOND_ATTRIBUTE
45765668 09-OCT-09 B2 67089 37B
45765670 09-OCT-09 BA 67089 P D
45765672 09-OCT-09 B6 67089 C
45765673 09-OCT-09 B4 67089 E 7
45765674 09-OCT-09 G1 23567 23567 W
45765675 09-OCT-09 M3 23567 Thanks so much! -
Version 10.2.0.4.0
I have a question on the expected behavior of the query below.
When I run the query below with the constraint on t1.partid = 789, I get the query result t2.Indicator showing "SPECIAL" as expected.
However, if I remove the constraint, and return all orders and parts, for the "789" part, the Indicator column is null.
select t1.orderid, t1.partid, t2.Indicator
from Orders a left outer join
select partid, 'SPECIAL' as Indicator
from vendors
where vendorname like '%ABC%'
) t2
on t1.partid = t2.partid
where t1.partid = '789'
I can address the issue with a case statement (below) or likely restructuring into a better statement.
But I'm just curious if this is expected or if there is some SQL rule being violated in the first example.
I tried to search for this to see if it was already addressed but didn't have much luck.
This works:
select t1.orderid, t1.partid,
case when t1.partid is not null then "SPECIAL" else null end as Indicator
from Orders a left outer join
select partid, 'SPECIAL' as Indicator
from vendors
where vendorname like '%ABC%'
) t2
on t1.partid = t2.partidSorry, it's been a while since I posted and should have read the rules. And I didn't properly reference the alias. So Post #1 was bad.
When I mockup a small set of data (shown below), I don't get the error. The original query actually joins to a few other (seemingly) irrelevant tables and I tried to simplify it here So I guess if I can't replicate it, then there might not be much assistance that can be provided.
This was more of a curiousity than anything else to see if perhaps someone came across this before.
For what it's worth:
create table t1 (orderid number,
partid varchar2(20)
create table t2
(vendorid varchar2(20),
partid varchar2(20)
insert into t1 values(1, '123');
insert into t1 values(2, '456');
insert into t1 values(3, '789');
insert into t2 values ('ABC','789');
insert into t2 values ('DEF','123');
insert into t2 values ('EFG','456');
insert into t2 values ('ABC','7891');
insert into t2 values ('DEF','1231');
insert into t2 values ('EFG','4561');
select t1.orderid, t1.partid, t2.Indicator
from t1 left outer join
select partid, 'SPECIAL' as Indicator
from t2
where vendorid like '%ABC%'
) t2
on t1.partid = t2.partid
the query that gives unexpected behavior is (although I can't replicate on this simplified version):
select t1.orderid, t1.partid, t2.Indicator
from t1 left outer join
select partid, 'SPECIAL' as Indicator
from t2
where vendorid like '%ABC%'
) t2
on t1.partid = t2.partid -
Hello,
I have two select statements as
Query 1 : Select col1,col2,col3,col4,value_a from table_1
Query 2: Select col1,col2,col3,col4,value_b from table_2
I want to join these two select statement to get below result.
col1 col2 col3 col4 value_a value_b
Scenario 1: Both query fecth the result
Result of query 1:
Col1 Col 2 Col3 Col4 Value_a
1 TK TL TM 100
Result of query 2:
Col1 Col 2 Col3 Col4 Value_b
1 TK TL TM 200
Ultimate join result should be
Col1 Col 2 Col3 Col4 Value_a value_b
1 TK TL TM 100 200
Scenario 2: Only query 1 fetches the result
Result of query 1:
Col1 Col 2 Col3 Col4 Value_a
1 TN TO TP 300
Result of query 2:
Col1 Col 2 Col3 Col4 Value_b
Ultimate join result should be
Col1 Col 2 Col3 Col4 Value_a value_b
1 TN TO TP 300 0
Scenario 3: Only query 2 fetches the result
Result of query 1:
Col1 Col 2 Col3 Col4 Value_a
Result of query 2:
Col1 Col 2 Col3 Col4 Value_b
1 TN TO TP 300
Ultimate join result should be
Col1 Col 2 Col3 Col4 Value_a value_b
1 TN TO TP 0 300
How should I join these?Because you want a FULL OUTER JOIN .
select
t1.*, t2.*
from
table_1 t1
full outer join table_2 t2
on
t2.col1 = t1.col1
and t2.col2 = t1.col2
and t2.col3 = t1.col3
and t2.col4 = t1.col4
)Please read the FAQ and learn how to post questions, so you can format your code, etc...
http://wiki.oracle.com/page/Oracle+Discussion+Forums+FAQ -
I have two Tables
Table A
ID VALUE
1 Delhi
2 Mumbai
3 Bangalore
Table B
TYPE TYPE_A_ID TYPE_B_ID
A 1 NA
A 1 NA
B NA 2
A 3 NA
B NA 1
A 1 NA I want to get the value from Table A, depending on the Type in Table B
i.e., when the Type is A, the value in Type_A_ID should be looked up in Table A
and when the Type is B, the value in Type_B_ID should be looked up in Table A.
The result how i need is as follows:
TYPE TYPE_A_ID TYPE_B_ID Value
A 1 NA Delhi
A 1 NA Delhi
B NA 2 Mumbai
A 3 NA Bangalore
B NA 1 Delhi
A 1 NA DelhiHere you go...
<pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>
SQL> DROP TABLE A;
Table dropped.
SQL> CREATE TABLE A ( ID INTEGER, VALUE VARCHAR2(20));
Table created.
SQL> INSERT INTO A VALUES(1,'Delhi');
1 row created.
SQL> INSERT INTO A VALUES(2,'Mumbai');
1 row created.
SQL> INSERT INTO A VALUES(3,'Bangalore');
1 row created.
SQL> DROP TABLE B;
Table dropped.
SQL> CREATE TABLE B(TYPE CHAR(1), TYPE_A_ID CHAR(2), TYPE_B_ID CHAR(2));
Table created.
SQL> INSERT INTO B VALUES ('A','1','NA');
1 row created.
SQL> INSERT INTO B VALUES ('A','1','NA');
1 row created.
SQL> INSERT INTO B VALUES ('B','NA','2');
1 row created.
SQL> INSERT INTO B VALUES ('A','3','NA');
1 row created.
SQL> INSERT INTO B VALUES ('B','NA','1');
1 row created.
SQL> INSERT INTO B VALUES ('A','1','NA');
1 row created.
SQL> COMMIT;
Commit complete.
SQL>
SQL> SELECT TYPE, TYPE_A_ID, TYPE_B_ID, VALUE
2 FROM A, (SELECT TYPE, TYPE_A_ID, TYPE_B_ID, DECODE(TYPE_A_ID,'NA',TYPE_B_ID,TYPE_A_ID) ID FROM B) B
3 WHERE A.ID = B.ID
4 /
T TY TY VALUE
A 1 NA Delhi
A 1 NA Delhi
B NA 1 Delhi
A 1 NA Delhi
B NA 2 Mumbai
A 3 NA Bangalore
6 rows selected.
</code></pre>
Karthick
http://www.karthickarp.blogspot.com/ -
Hi, How I can get desired result. I am joining two tables but if date timeline does't exist in #two table then should show hyphen (-). Please help on this query. Thanks.
create table #one (code_p char(4), code_h char(2), code_date datetime)
insert into #one values ('DEHG','2','2010-01-01')
insert into #one values ('DEHG','2','2011-01-01')
insert into #one values ('DEHC','2','2009-01-01')
insert into #one values ('DEHG','2','2012-01-01')
create table #two (code_p char(4), code_h char(2), code_date datetime)
insert into #two values ('DEHG','2','2010-01-01')
insert into #two values ('DEHC','2','2009-01-01')
select p.code_p code_p_one, p.code_h code_h_one, p.code_date code_date_one,
p.code_p code_p_two, p.code_h code_h_two, p.code_date code_date_two from #one p join #two a on p.code_p = a.code_p
--Result from the above query
code_p_one code_h_one code_date_one code_p_two code_h_two code_date_two
DEHG 2 2010-01-01 DEHG 2 2010-01-01
DEHG 2 2011-01-01 DEHG 2 2010-01-01
DEHC 2 2009-01-01 DEHG 2 2009-01-01
DEHC 2 2012-01-01 DEHG 2 2009-01-01
--Desired result
code_p_one code_h_one code_date_one code_p_two code_h_two code_date_two
DEHG 2 2010-01-01 DEHG 2 2010-01-01
DEHG 2 2011-01-01 DEHG 2 -
DEHC 2 2009-01-01 DEHG 2 2009-01-01
DEHC 2 2012-01-01 DEHG 2 -Try this:
select p.code_p code_p_one, p.code_h code_h_one, p.code_date code_date_one,
p.code_p code_p_two, p.code_h code_h_two, ISNULL(CONVERT(varchar(50),a.code_date,121),'-') code_date_two
from #one p
left join #two a on p.code_p = a.code_p and p.code_date=a.code_date
If this post answers your query, please click "Mark As Answer" or "Vote as Helpful". -
Query problem, two working queries how to left join together?
Hello,
I have a two queries that I have been trying to put together for a couple days. I'm frazzled. Hopefully you can help.
The first query returns all rows from the database. The second query returns only one row (because the way it is currentlly set up in the Where clause). So I know that will have to change. For each row returned in Query1, I need the two fields from Query2 included
(so the link would be through client.Id (which is an indexed field) or client.Accountnumber?
This query, returns all records in the database:
Select client.Id, client.accountnumber, client.Namelast,
dmlocation.city ||', '||dmlocation.state as CityState,
client.salesTerritory_client ||'-'|| dmuser.namefirst_user ||' '|| dmuser.namelast_user as Territory,
MaxDates.LastRun, client.creditrisk, client.customercategory
from client
Left join fctclientcoverage on fctclientcoverage.client_id = client.id
Left join dmlocation on fctclientcoverage.location_id = dmlocation.id
Left join dmuser on dmuser.id = client.id
Left join (Select to_char(Max(dmdate.calendardate),'MM/DD/YY') as LastRun, Client.Id
from dmdate, client, fctadorder
where dmdate.id = fctadorder.lastinsert_date_id and client.id = fctadorder.primaryorderer_client_id
group by client.id) MaxDates ON client.id = MaxDates.Id
where(fctclientcoverage.Ccoverrecordstopdate Is Null)
Order by client.namelast;
Query 2, only returns 1 row, so for each row returned above, the two fields selected in this query should accompany each row. But how to link these two selects using the client.accountnumber (or perhaps by dmcliet.id)?
Select booked.CurRev, booked.LastRev from (
Select (sum(Case When dmDate.CalendarDate >= '29-DEC-2008' and dmDate.CalendarDate < '
Then fctinsertchargedetail.Amount_insertDetail Else 0 End)) As CurRev,
(sum(Case When dmDate.CalendarDate >= '29-DEC-2007' and dmDate.CalendarDate < '
Then fctinsertchargedetail.Amount_insertDetail Else 0 End)) As LastRev
from fctAdorder
Inner Join client On fctAdorder.primaryorderer_client_id = client.id
Inner Join fctinsertion On fctAdorder.id=fctinsertion.fctAdorder_id
Inner Join fctinsertchargesummary On fctinsertion.id=fctinsertchargesummary.insertion_id
Inner Join dmDate On fctinsertion.insert_date_id=dmDate.id
Inner Join fctinsertchargedetail On fctinsertchargesummary.id=fctinsertchargedetail.insertchargesummary_id
WHERE client.accountnumber = '12345678' and
dmDate.CalendarDate >= '29-DEC-2007' And dmDate.CalendarDate < ') booked;
Thanks for your time.Yes, You are correct!
I just recently got the query working with the aid of another forum.
The sad part is, all though the first query took 11 seconds to return 180,000 rows (thats good); The second query took 4 minutes to calculate and return all it's rows (that's bad). Together the query ran for over 4 minutes. Way too slow.
Being brand new to oracle I have to try and figure away to cut this time down. Perhaps I'm not considering something?
I orginally brought into my .net app the results from the first query and then in the rowdatabound event I queried each row to get the information needed from the second query. That was way too slow also. It was recommended to try and return all needed data at once.
I've been given a task to emulate a current application, (which I do not have access to it's code), that brings back all of this same information that I am using. It only takes them maybe 15 seconds to run, to bring back all. Of course they were experienced oracle sql developers.
So I guess my next step is to try and improve that second query. Thanks for replying to this Frank. I'll be back. Are you or is anyone good at knowing how to optimzie queries? I'm reading a book now trying out suggestions. Nothing is working yet.
thanks -
How to generate a query involving multiple tables(one left join others)
Hi, all,
I want to query a db like these:
I need all the demographics information(from table demo) and their acr info(from table acr), and their clinical info(from table clinical), and their lab info(from table lab).
The db is like this:
demo->acr: one to many
demo->clinical info: one to many
demo->lab info: one to many
I want to get one query result which are demo left join acr, and demo left join clinical, and demo left join lab. I hope the result is a record including demo info, acr info, clinical info, and lab info.
How could I do this in SQL?
Thanks a lot!
QianThank you very, very much!
Actually, I need a huge query to include all the tables in our db.
We are running a clinical db which collects the patients demographics info, clinical info, lab info, and many other information.
The Demographics table is a center hub which connects other tables. This is the main architecture.
My boss needed a huge query to include all the information, so others could find what they need by filtering.
As you have found, because one patients usually has multiple clinical/lab info sets, so the result will be multiplied! the number of result=n*m*k*...
My first plan is to set time point criteria to narrow all the records with one study year. If somebody needs to compare them, then I have to show them all.
So I have to know the SQL to generate a huge query including as many tables as possible.
I show some details here:
CREATE TABLE "IMMUNODATA"."DEMOGRAPHICS" (
"SUBJECTID" INTEGER NOT NULL,
"WORKID" INTEGER,
"OMRFHISTORYNUMBER" INTEGER,
"OTHERID" INTEGER,
"BARCODE" INTEGER,
"GENDER" VARCHAR2(1),
"DOB" DATE,
"RACEAI" INTEGER,
"RACECAUCASIAN" INTEGER,
"RACEAA" INTEGER,
"RACEASIAN" INTEGER,
"RACEPAC" INTEGER,
"RACEHIS" INTEGER,
"RACEOTHER" VARCHAR2(50),
"SSN" VARCHAR2(11),
PRIMARY KEY("SUBJECTID") VALIDATE
CREATE TABLE "IMMUNODATA"."ACR" (
"ID" INTEGER NOT NULL,
"THEDATE" DATE ,
"SUBJECTID" INTEGER NOT NULL,
"ACR_PAGENOTCOMPLETED" VARCHAR2(1000) ,
"ACR_MALARRASHTODAY" INTEGER ,
"ACR_MALARRASHEVER" INTEGER ,
"ACR_MALARRSHEARLIESTDATE" DATE ,
PRIMARY KEY("ID") VALIDATE,
FOREIGN KEY("SUBJECTID") REFERENCES "IMMUNODATA"."DEMOGRAPHICS" ("SUBJECTID") VALIDATE
CREATE TABLE "IMMUNODATA"."CLIN" (
"ID" INTEGER NOT NULL,
"THEDATE" DATE ,
"SUBJECTID" INTEGER NOT NULL,
"CLIN_PAGENOTCOMPLETED" VARCHAR2(1000) ,
"CLIN_FATIGUE" VARCHAR2(20) ,
"CLIN_FATIGUEDATE" DATE ,
"CLIN_FEVER" VARCHAR2(20) ,
"CLIN_FEVERDATE" DATE ,
"CLIN_WEIGHTLOSS" VARCHAR2(20) ,
"CLIN_WEIGHTLOSSDATE" DATE ,
"CLIN_CARDIOMEGALY" VARCHAR2(20) ,
PRIMARY KEY("ID") VALIDATE,
FOREIGN KEY("SUBJECTID") REFERENCES "IMMUNODATA"."DEMOGRAPHICS" ("SUBJECTID") VALIDATE
Other tables are alike.
Thank very much!
Qian -
Help with Inner Join query in SQL
Hope someone can help with this, as this is quite an involved project for me, and I'm just about there with it.
My table structure is :
table_packages
packageID
package
packageDetails
etc
table_destinations
destinationID
destination
destinationDetails
etc
table_packagedestinations
packageID
destinationID
..so nothing that complicated.
So the idea is that I can have a package details page which shows the details of the package, along any destinations linked to that package via the packagedestinations table.
So this is the last part really - to get the page to display the destinations, but I'm missing something along the way....
This is the PHP from the header, including my INNER JOIN query....
PHP Code:
<?php
$ParampackageID_WADApackages = "-1";
if (isset($_GET['packageID'])) {
$ParampackageID_WADApackages = (get_magic_quotes_gpc()) ? $_GET['packageID'] : addslashes($_GET['packageID']);
$ParamSessionpackageID_WADApackages = "-1";
if (isset($_SESSION['WADA_Insert_packages'])) {
$ParamSessionpackageID_WADApackages = (get_magic_quotes_gpc()) ? $_SESSION['WADA_Insert_packages'] : addslashes($_SESSION['WADA_Insert_packages']);
$ParampackageID2_WADApackages = "-1";
if (isset($_GET['packageID'])) {
$ParampackageID2_WADApackages = (get_magic_quotes_gpc()) ? $_GET['packageID'] : addslashes($_GET['packageID']);
mysql_select_db($database_connPackages, $connPackages);
$query_WADApackages = sprintf("SELECT packageID, package, costperpax, duration, baselocation, category, dateadded, agerange, hotel, educational_tours, field_trips, corporate_outings, plant_visits, budget_package, rollingtours, teambuilding, description, offer FROM packages WHERE packageID = %s OR ( -1= %s AND packageID= %s)", GetSQLValueString($ParampackageID_WADApackages, "int"),GetSQLValueString($ParampackageID2_WADApackages, "int"),GetSQLValueString($ParamSessionpackageID_WADApackages, "int"));
$WADApackages = mysql_query($query_WADApackages, $connPackages) or die(mysql_error());
$row_WADApackages = mysql_fetch_assoc($WADApackages);
$totalRows_WADApackages = mysql_num_rows($WADApackages);
$colname_educationalDestinations = "1";
if (isset($_GET['PackageID'])) {
$colname_educationalDestinations = (get_magic_quotes_gpc()) ? packageID : addslashes(packageID);
mysql_select_db($database_connPackages, $connPackages);
$query_educationalDestinations = sprintf("SELECT * FROM destinations INNER JOIN (packages INNER JOIN packagedestinations ON packages.packageID = packagedestinations.packageID) ON destinations.destinationID = packagedestinations.destinationID WHERE packages.packageID = %s ORDER BY destination ASC", GetSQLValueString($colname_educationalDestinations, "int"));
$educationalDestinations = mysql_query($query_educationalDestinations, $connPackages) or die(mysql_error());
$row_educationalDestinations = mysql_fetch_assoc($educationalDestinations);
$totalRows_educationalDestinations = mysql_num_rows($educationalDestinations);
?>
And where I'm trying to display the destinations themselves, I have :
<table>
<tr>
<td>Destinations :</td>
</tr>
<?php do { ?>
<tr>
<td><?php echo $row_educationalDestinations['destination']; ?></td>
</tr>
<?php } while ($row_educationalDestinations = mysql_fetch_assoc($educationalDestinations)); ?>
</table>
If anyone could have a quick look and help me out that would be much appreciated - not sure if its my SQL at the top, or the PHP in the page, but either way it would be good to get it working.
Thanks.First off, you need to get the database tables so that there is a relationship between them.
In fact, if there is a one to one relationship, then it may be better to store all of your information in one table such as
table_packages
packageID
package
packageDetails
destination
destinationDetails
etc
If there is a one to many relationship, then the following would be true
packages
packageID
package
packageDetails
etc
destinations
destinationID
packageID
destination
destinationDetails
etc
The above assumes that there are many destinations to one package with the relationship coloured orange.
Once you have the above correct you can apply your query as follows
SELECT *
FROM packages
INNER JOIN destinations
ON packages.packageID = destinations.packageID
WHERE packages.packageID = %s
ORDER BY destination ASC
The above query will show all packages with relevant destinations -
Filter on "---" in Left Outer Join Query
Hi guys,
very basic question but I have not found an answer, yet. I built an left outer join MDO query and need to select all those dataset that did not find a "partner", that is fields are set to "---". However, I do not manage to filter on '---', NULL...
When using SQL, it appears to be a String "---" but in MDO???Hey guys, found out that IS NULL needs to be used in query. Anyway, it appears to cause problems somewhere else.
I placed an IS NULL filter expression inside a join query but query did not return any results when called in by transaction. After removing this line, both NULL and NOT NULL data were returned. When used in test mode, IS NULL was working fine...
Maybe you are looking for
-
How do you add a custom label to dates in contacts.....
How do you add a custom label to dates in contacts- I have multiple birthdays in contact group and want to change label through customise to add additional birthday- unless another way to add second birthday to contacts and identify each one?????? or
-
My "4" won't turn on. It won't charge when connected to a charger or to the computer. It's never been dropped, or had any water damage. It looks like its brand new! The warranty ran on on Feb 23rd, help!!!
-
I'm pretty new at installing exchange myself and have never done Exchange 2013 While going through the install help online I came across disjointed domains. I think I'm over thinking this but here is what I have and what I want to do. Any other tips
-
Trying to restored my 4s but I get an unknown error occured (9)
trying to restore my 4s but i get an unknow error occured (9)
-
Enchancement to modify basic start date
Hi guys, I have craeated a project with the enchancement IWO10001 with the include ZXWO1U01 but when I enter to write my program using the fields 'GLTRP_EXP' and 'GSTRP_EXP' the system don't recognize this fields.Why?These fields are the fields of th