SQL Join query help
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
Similar Messages
-
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. -
Hi I have 3 tables.
Table columns
1. Buy buyer,sellername
2. IM product,hdate,UOM,dept,sec,subsec
3. stud dept,sec,subsecRequired O/P with columns as :
buyer product dept sec subsec
---------------------------------------------------so please send me the join query for this.
Thank you.I am getting the output with the above mentioned query as
buyer product dept class subsecs
90 glass 203 310 234
120 glass 203 310 234
354 glass 203 310 234
435 belts 330 243 890
435 belts 330 243 890
...like this I am getting the result...
So please help me in this issue..
Thank you. -
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" -
I know this is a SQL question but I can't seem to figure this
out. The below SQL query will run without error however it will
output the company_name for every row which I dont want.
So basicly it currently outputs like this now:
company_name - apple
company_name - dell
BUT want it to output like this:
company_name - apple,dell
MY CURRENT QUERY:
SELECT d.disputeid, t.company_name, t.tlid, t.type,
l.description
FROM member_disputes d, member_tradeline t, letters l
WHERE d.fk_tlid = t.tlid
AND d.fk_letterid = l.letterid
AND d.fk_memberid = #GetAuthUser()#
Any help much appreciatedquote:
Originally posted by:
LionelR
I know this is a SQL question but I can't seem to figure this
out. The below SQL query will run without error however it will
output the company_name for every row which I dont want.
So basicly it currently outputs like this now:
company_name - apple
company_name - dell
BUT want it to output like this:
company_name - apple,dell
MY CURRENT QUERY:
SELECT d.disputeid, t.company_name, t.tlid, t.type,
l.description
FROM member_disputes d, member_tradeline t, letters l
WHERE d.fk_tlid = t.tlid
AND d.fk_letterid = l.letterid
AND d.fk_memberid = #GetAuthUser()#
Any help much appreciated
Suddenly a light bulb illuminated over my head.
<cfouput>
company_name - #ValueList(yourquery.company_name)#
</cfoutput>
If that doesn't work, either change this, "t.company_name" to
"company_name" or "t.company_name as company_name".
I can't believe none of us thought of this earlier. -
SQL SELECT Query Help ..Please its very Urgent!!
Hi All,
I am having Oracle Database whice is storing 1000's of records daily.
I need to select some information based on date and time.
I am having two coloumns for Date and time. The first column(testDate) of type Date stores date as MM/DD/YY format and the second column(testTime)of type Numeric stores the time in seconds.
The Example data is :
testDate ------=-- testTime
11/12/2002 --- 35000
11/12/2002 --- 43000
11/12/2002 --- 45000
11/12/2002 --- 75000
11/13/2002 --- 2000
11/13/2002 --- 3500
11/13/2002 --- 4300
11/13/2002 --- 9800
11/13/2002 --- 23000
11/14/2002 --- 5000
11/14/2002 --- 10000
11/14/2002 --- 15000
How can i write a SELECT Query to get the records of specific date and seconds to next day specific date and seconds.I mean i want all the records between 11/12/2002 --- 43000 seconds to 11/14/2002 --- 1000 seconds.
If any one helps me in this regard iam very thank full to them.Its very urgent for me.
ThanksHi m7nra,
I used the query as
SELECT * FROM table
WHERE testDate + (testTime/(24*60*60)) BETWEEN TO_DATE('MM/DD/YYYY','12.11.2002') AND TO_DATE('MM/DD/YYYY','14.11.2002')
its giving DATE FORMAT NOT RECOGNIZED error.
The Example data is :
testDate ------=-- testTime
11/12/2002 --- 35000
11/12/2002 --- 43000
11/12/2002 --- 45000
11/12/2002 --- 75000
11/13/2002 --- 2000
11/13/2002 --- 3500
11/13/2002 --- 4300
11/13/2002 --- 9800
11/13/2002 --- 23000
11/14/2002 --- 5000
11/14/2002 --- 10000
11/14/2002 --- 15000
infact i need all the records between 11/12/2002 --- 43000 seconds to 11/14/2002 --- 1000 seconds.
Please help me to find a full query beacuse iam very new to Oracle.
Thanks,
S R Mannava -
HUM ADG DYS (NIA, SIM, TRC, TRX) SMALL BRANDS (LUP, KAL,CRN,LPP,SYN)
MON TUE WED THURS FRI MON TUE WED THURS FRI MON TUE WED THURS FRI MON TUE WED THURS FRI
VENDOR
INT
QUAN
STER
LASH
OSP
HIB
PROD
I’d like to put together a query to populate the tables above,like count of recods for each vendor for each brand with the criteria for selecting within one week.
Here vendor_cd(INT,QUAN,STER,...etc),brand_cd(HUM,ADG,NIA,SIM,..eyc).we are extracting the details from file detail table whose column are like FILE_ID,FILE_RECEIPT_TS,REC_INSERT_TS,VENDOR_CD,BRAND_CD,RECORD_COUNT.
Edited by: ASHWINI89 on Mar 21, 2013 8:33 PMWelcome to the forum!!
Please consider the following when you post a question. This would help us help you better
1. New features keep coming in every oracle version so please provide Your Oracle DB Version to get the best possible answer.
You can use the following query and do a copy past of the output.
select * from v$version 2. This forum has a very good Search Feature. Please use that before posting your question. Because for most of the questions
that are asked the answer is already there.
3. We dont know your DB structure or How your Data is. So you need to let us know. The best way would be to give some sample data like this.
I have the following table called sales
with sales
as
select 1 sales_id, 1 prod_id, 1001 inv_num, 120 qty from dual
union all
select 2 sales_id, 1 prod_id, 1002 inv_num, 25 qty from dual
select *
from sales 4. Rather than telling what you want in words its more easier when you give your expected output.
For example in the above sales table, I want to know the total quantity and number of invoice for each product.
The output should look like this
Prod_id sum_qty count_inv
1 145 2 5. When ever you get an error message post the entire error message. With the Error Number, The message and the Line number.
6. Next thing is a very important thing to remember. Please post only well formatted code. Unformatted code is very hard to read.
Your code format gets lost when you post it in the Oracle Forum. So in order to preserve it you need to
use the {noformat}{noformat} tags.
The usage of the tag is like this.
<place your code here>\
7. If you are posting a *Performance Related Question*. Please read
{thread:id=501834} and {thread:id=863295}.
Following those guide will be very helpful.
8. Please keep in mind that this is a public forum. Here No question is URGENT.
So use of words like *URGENT* or *ASAP* (As Soon As Possible) are considered to be rude. -
I have four tables and I want to create one XML file. I provided the temp tables with
data and expected output.
create table #ZDL(ZLN bigint, ZTLA int, ZMR decimal, ZCLS varchar(20), ZPITIP money)
insert into #ZDL values(1234, 200000, 8.5, 'CART', 1500.00)
create table #ZBL(ZLN bigint, ZBN varchar(50), ZFN varchar(20), ZMN varchar(8), ZLL varchar(20))
insert into #ZBL values(1234, 'TEST Test', 'TEST', null, 'Test')
create table #ZCC(ZLN bigint, ZSN int, ZCE int)
insert into #ZCC values(1234, 1, 4)
create table #ZP(ZLN bigint, ZPT varchar(50), ZPP int, ZNU int)
insert into #ZP values(1234, 'Attached', 6500, 3)
Expected XML Result should be:
<TEST_DATA xmlns="http://www.TestData.com/Schema/Test"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.TestData.com/Schema/Test_Schema.xsd">
<KEY _Name="ZID" _Value="789" _ID="ZID"/>
<ZL>
<ZLN>1234</ZLN>
<ZTLA>200000</ZTLA>
<ZMR>8.5</ZMR>
<ZCLS>CART</ZCLS>
<ZPITIP>1500.00</ZPITIP>
</ZL>
<ZBS>
<ZB>
<ZBN>TEST Test</ZBN>
<ZFN>TEST</ZFN>
<ZMN></ZMN>
<ZLL>Test</ZLL>
</ZB>
</ZBS>
<ZCC>
<ZC>
<ZSN>1</ZSN>
<ZCE>4</ZCE>
</ZC>
</ZCC>
<ZP>
<ZPT>Attached</ZPT>
<ZPP>6500</ZPP>
<ZNU>3</ZNU>
</ZP>
</TEST_DATA>
Thankslittle change in your query as OP expected
SELECT
(SELECT ZLN ,
ZTLA ,
ZMR ,
ZCLS,
ZPITIP --AS [*]
FROM #ZDL
WHERE ZLN = z1.ZLN
FOR XML PATH('ZL'),TYPE) AS [*],
(SELECT
ZBN ,--AS [*],
ZFN ,
ISNULL(ZMN,'') AS ZMN ,
ZLL
FROM #ZBL
WHERE ZLN = z1.ZLN
FOR XML PATH('ZB'),TYPE) AS [ZBS],
(SELECT
ZSN,ZCE
FROM #ZCC
WHERE ZLN = z1.ZLN
FOR XML PATH('ZC'),TYPE) AS [ZCC],
(SELECT
ZPT,
ZPP,
ZNU
FROM #ZP
WHERE ZLN = z1.ZLN
FOR XML PATH('ZP'),TYPE) AS [*]
FROM (SELECT DISTINCT ZLN FROM #ZDL) z1
FOR XML PATH('TEST_DATA')
Nope
it will give different output
see the difference
mine
<TEST_DATA>
<ZL>
<ZLN>1234</ZLN>
<ZTLA>200000</ZTLA>
<ZMR>9</ZMR>
<ZCLS>CART</ZCLS>
1500.0000
</ZL>
<ZBS>
<ZB>
TEST Test
<ZFN>TEST</ZFN>
<ZMN />
<ZLL>Test</ZLL>
</ZB>
</ZBS>
<ZCC>
<ZC>
<ZSN>1</ZSN>
<ZCE>4</ZCE>
</ZC>
</ZCC>
<ZP>
<ZPT>Attached</ZPT>
<ZPP>6500</ZPP>
<ZNU>3</ZNU>
</ZP>
</TEST_DATA>
and see your output
<TEST_DATA>
<ZL>
<ZLN>1234</ZLN>
<ZTLA>200000</ZTLA>
<ZMR>9</ZMR>
<ZCLS>CART</ZCLS>
<ZPITIP>1500.0000</ZPITIP>
</ZL>
<ZBS>
<ZB>
<ZBN>TEST Test</ZBN>
<ZFN>TEST</ZFN>
<ZMN />
<ZLL>Test</ZLL>
</ZB>
</ZBS>
<ZCC>
<ZC>
<ZSN>1</ZSN>
<ZCE>4</ZCE>
</ZC>
</ZCC>
<ZP>
<ZPT>Attached</ZPT>
<ZPP>6500</ZPP>
<ZNU>3</ZNU>
</ZP>
</TEST_DATA>
Its different from what Op wanted
my suggestion gives exactly in the format wanted
notice extra nodes ZPITIP and ZLN
coming in your case
Your original suggestion also has this issues
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
Hi All,
I have below table
IT_Terms_First_Date
IT_Terms_Last_Date
DI_Debt_Num
IT_Terms_Seq_Num
200501
201101
1000
131
200512
203412
1001
131
200503
204209
1003
131
200507
201001
1004
131
200510
202710
1005
131
200506
202412
10020
131
197910
198310
257000
101
198009
202909
298000
101
198101
202908
298000
103
198105
202910
298000
104
199109
201309
578000
101
199204
201110
600000
101
198009
201010
298010
101
198105
204010
298010
104
201011
202909
298010
103
I need to check whether my DI_Debt_Num having Ovelaping or not for each DI_Debt_Num,
at this moment we are checking each row in loop and usnig function
exec @Overlap1=[DffMonths] @ITtermsLD,@ITtermsNextFD
exec @Overlap2=[DffMonths] @ITtermsFD,@ITtermsNextFD
exec @Overlap3=[DffMonths] @ITtermsFD,@ITtermsNextLD
if(@Overlap1>0 and (@Overlap2<=0 OR @Overlap3<0))
BEGIN
SET @CheckOverlap=1
END
here @ITtermsLD is the IT_Terms_Last_Date of the current DI_Debt_Num,@ITtermsNextFD is the IT_Terms_First_Date of the next row. @ITtermsFD is the IT_Terms_First_Date of the current month
if we consider the 298000 DI_Debt_Num we have 3 IT_Terms_Seq_Num 101,103,104
in this senario we need to check only the first 2 rows from that itself we can identify it is overlapped ,but when we consider the 298010 we need to check all 3 IT_Terms_Seq_Num 101,103,104 if we consider first two rows 101 & 103 it is not overlapped.Then
we have to check first row with 3rd row ie 104 and it is overlapped.We are checking the overlap senario for DI_Debt_Num having multipple IT_Terms_Seq_Num rows
Some situation first row may not be overlapped with other rows .Then we have to check the 2nd row with the next rows in the same way we are doing for first row
My aim is to covert this looping method to a select query to improve my query performance
Thanks in advance
RoshanPlease post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. You have no idea,
do you? Temporal data should use ISO-8601 formats. You failed again! I will guess that your dates are months. Code should be in Standard SQL as much as possible and not local dialect.
This is minimal polite behavior on SQL forums.
>> I have below table <<
This is not a table! Where is the DDL? This picture has no name. Not even a name!! There is no “seq_nbr” in RDBMS; it has to be a “<something in particular>_seq” and there are no duplicates in a sequence.
My guess is that each di_debt_nbr has a sequence within its range. I will call it the “foobar_seq” for lack of a name.
My next guess is that your dates are really months and you do not know about using a report period table. This idiom gives a name to a range of dates that is common to the entire enterprise.
CREATE TABLE Something_Report_Periods
(something_report_name CHAR(10) NOT NULL PRIMARY KEY
CHECK (something_report_name LIKE <pattern>),
something_report_start_date DATE NOT NULL,
something_report_end_date DATE NOT NULL,
CONSTRAINT date_ordering
CHECK (something_report_start_date <= something_report_end_date),
etc);
These report periods can overlap or have gaps. I like the MySQL convention of using double zeroes for months and years, That is 'yyyy-mm-00' for a month within a year and 'yyyy-00-00' for the whole year. The advantages are that it will sort with the ISO-8601
data format required by Standard SQL and it is language independent. The pattern for validation is '[12][0-9][0-9][0-9]-00-00' and '[12][0-9][0-9][0-9]-[01][0-9]-00'
Here is another guess at what you want, if you knew what a table is:
CREATE TABLE DI_Debts
(it_terms_first_date CHAR(10) NOT NULL
REFERENCES Report_Period (month_name),
it_terms_last_date CHAR(10) NOT NULL
REFERENCES Report_Period (month_name),
CHECK (it_terms_first_date <= it_terms_last_date),
di_debt_nbr INTEGER NOT NULL,
foobar_seq INTEGER NOT NULL,
PRIMARY KEY (di_debt_nbr, foobar_seq));
INSERT INTO DI_Debts
VALUES
('2005-01-00', '2011-01-00', 1000, 1),
('2005-12-00', '2034-12-00', 1001, 1),
('2005-03-00', '2042-09-00', 1003, 1),
('2005-07-00', '2010-01-00', 1004, 1),
('2005-10-00', '2027-10-00', 1005, 1),
('2005-06-00', '2024-12-00', 100201, 1),
('1979-10-00', '1983-10-00', 257000, 1),
('1980-09-00', '2029-09-00', 2980001, 1),
('1981-01-00', '2029-08-00', 298000, 1),
('1981-05-00', '2029-10-00', 298000, 2),
('1991-09-00', '2013-09-00', 578000, 1),
('1992-04-00', '2011-10-00', 600000, 1),
('1980-09-00', '2010-10-00', 298010, 1),
('1981-05-00', '2040-10-00', 298010, 2),
('2010-11-00', '2029-09-00', 298010, 3);
I need to check whether my DI_Debt_nbr are overlapping or not for each DI_Debt_nbr,
>> at this moment we are checking each row in loop and using function
exec @Overlap1=[DffMonths] @IttermsLD, @ITtermsNextFD;
exec @Overlap2=[DffMonths] @IttermsFD, @ITtermsNextFD;
exec @Overlap3=[DffMonths] @IttermsFD, @ITtermsNextLD; <<
And you were too rude to post the code for these functions! You write SQL with assembly language flags! We do not do that! We also would use a CASE expression, and not IF-THEN control flow in SQL.
Did you know that ANSI/ISO Standard SQL has a temporal <overlaps predicate>? Notice the code to handle NULLs and the ISO half-open interval model.
(start_date_1 > start_date_2
AND NOT (start_date_1 >= end_date_2
AND end_date_1 >= end_date_2))
OR (start_date_2 > start_date_1
AND NOT (start_date_2 >= end_date_1
AND end_date_2 >= end_date_1))
OR (start_date_1 = start_date_2
AND (end_date_1 <> end_date_2 OR end_date_1 = end_date_2))
I tend to prefer the use of a calendar table. NULLs return an empty set, as above.
EXISTS
((SELECT cal_date FROM Calendar
WHERE cal_date BETWEEN start_date_1 AND end_date_1)
INTERSECT
(SELECT cal_date FROM Calendar
WHERE cal_date BETWEEN start_date_2 AND end_date_2))
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL -
I'm trying to figure out which table/column it is that holds a particular value from the application I am using.
I need a SQL query that will interrogate the database based on the value of a particur colunmn so that it returns and column_name that has a value called 'www.google.com' contained in it and the associated table_name
Any ideas?
Thanks!One of Michaels examples...
michaels> var val varchar2(5)
michaels> exec :val := 'as'
PL/SQL procedure successfully completed.
michaels> select distinct substr (:val, 1, 11) "Searchword",
substr (table_name, 1, 14) "Table",
substr (t.column_value.getstringval (), 1, 50) "Column/Value"
from cols,
table
(xmlsequence
(dbms_xmlgen.getxmltype ('select ' || column_name
|| ' from ' || table_name
|| ' where upper('
|| column_name
|| ') like upper(''%' || :val
|| '%'')'
).extract ('ROWSET/ROW/*')
) t
-- where table_name in ('EMPLOYEES', 'JOB_HISTORY', 'DEPARTMENTS')
order by "Table"Example of it working...
SQL> ed
Wrote file afiedt.buf
1 select distinct substr (table_name, 1, 14) "Table",
2 substr (t.column_value.getstringval (), 1, 50) "Column/Value"
3 from cols,
4 table
5 (xmlsequence
6 (dbms_xmlgen.getxmltype ('select ' || column_name
7 || ' from ' || table_name
8 || ' where upper('
9 || column_name
10 || ') like upper(''%' || 'SCOTT'
11 || '%'')'
12 ).extract ('ROWSET/ROW/*')
13 )
14 ) t
15 where table_name in ('EMP', 'DEPT')
16* order by "Table"
SQL> /
Table Column/Value
EMP <ENAME>SCOTT</ENAME>
SQL> -
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/ -
I have four table like below:
CREATE TABLE Party ( PartyID int identity(1,1)not null, PartyRegisteredDate datetime, MemberNo varchar(16), SubsNo varchar(9), PerNo varchar(2) )
CREATE TABLE Contract ( ContractID int identity(1,1)not null, PartyID int, MemberNo varchar(16), SubsNo varchar(9), PerNo varchar(2) , ContractStartDate datetime, ContractEndDate datetime)
CREATE TABLE IndividualContract ( IndContractID int identity(1,1)not null, ContractID int, PartyID int, MemberNo varchar(16), SubsNo varchar(9), PerNo varchar(2) ,ContractStartDate datetime, ContractEndDate datetime )
CREATE TABLE Customer ( CustomerID int, IndContractID int, ContractID int, MemberNo varchar(16), SubsNo varchar(9), PerNo varchar(2))
The business Key is MemberNo, SubsNo, PerNo in all the 4 tables.
Contract table has PartyID as foreignKey from Party table
IndividualContract table has ContractID,PartyID as foreignKeys from Party table and Contract table.
Customer table has IndContractID,ContractID as foreignKeys from IndividualContract table.
CustomerID in Customer table is nothing but PartyID.
IndividualContract and Customer tables should be one-one.
--Below is the source data in #Source table
Create Table #Source (MemberNo varchar(16), SubsNo varchar(9), PerNo varchar(2),PartyRegisteredDate datetime, ContractStartDate datetime, ContractEndDate datetime)
Insert into #Source
Select '054911', '079548709', '01', '2002-09-01 00:00:00.000', '2012-08-01 00:00:00.000', '9999-12-31 00:00:00.000' union all
Select '824212', '091547708', '01', '1987-07-14 00:00:00.000', '1987-07-14 00:00:00.000', '2010-09-01 00:00:00.000' union all
Select '864211', '041609336', '01', '1993-01-01 00:00:00.000', '1999-03-01 00:00:00.000', '1999-12-31 00:00:00.000' union all
Select '864212', '113523275', '01', '1993-01-01 00:00:00.000', '1998-06-01 00:00:00.000', '1999-12-31 00:00:00.000' union all
Select '824212', '079548709', '02', '1987-07-14 00:00:00.000', '2010-09-01 00:00:00.000', '2010-09-01 00:00:00.000' union all
Select '864211', '113523275', '02', '1993-01-01 00:00:00.000', '1999-03-01 00:00:00.000', '1999-12-31 00:00:00.000' union all
Select '864212', '041609336', '02', '1993-01-01 00:00:00.000', '1998-05-01 00:00:00.000', '1999-12-31 00:00:00.000' union all
Select '864212', '091547708', '03', '1993-01-01 00:00:00.000', '1998-06-01 00:00:00.000', '1999-12-31 00:00:00.000' union all
Select '867616', '041609336', '03', '1993-04-05 00:00:00.000', '1998-05-01 00:00:00.000', '1999-12-31 00:00:00.000' union all
Select '867616', '113523275', '03', '1993-04-05 00:00:00.000', '1998-06-01 00:00:00.000', '1999-12-31 00:00:00.000'
This source data should go to the above 4 tables.
But the requirement is:
1. For one MemberNo there should be only one row in Party table. So in my case ,the party table should have only 5 rows like below.
PartyID PartyRegisteredDate MemberNo SubsNo PerNo
1 1987-07-14 00:00:00.000 824212 091547708 01
2 1993-01-01 00:00:00.000 864211 041609336 01
3 1993-01-01 00:00:00.000 864212 113523275 01
4 1993-04-05 00:00:00.000 867616 041609336 03
5 2002-09-01 00:00:00.000 054911 079548709 01
2. The contract table should have only records with PerNo='01' for one MemberNo.So in my case this table should have like below.
ContractID PartyID MemberNo SubsNo PerNo ContractStartDate ContractEndDate
1 1 824212 091547708 01 1987-07-14 00:00:00.000 2010-09-01 00:00:00.000
2 2 864211 041609336 01 1993-01-01 00:00:00.000 1999-12-31 00:00:00.000
3 3 864212 113523275 01 1993-01-01 00:00:00.000 1999-12-31 00:00:00.000
4 5 054911 079548709 01 2002-09-01 00:00:00.000 9999-12-31 00:00:00.000
3. The IndividualContract and Customer should have all the records from #Source table, as IndividualContract and Customer tables are one-one.
4. IndivuidialContract table should look like below:
Here the ContractID is based on the SubsNo from Contract table.
IndContractID ContractID PartyID MemberNo SubsNo PerNo ContractStartDate ContractEndDate
1 1 1 824212 091547708 01 1987-07-14 00:00:00.000 1988-09-30 00:00:00.000
2 4 1 824212 079548709 02 2010-09-01 00:00:00.000 2010-09-01 00:00:00.000
3 2 2 864211 041609336 01 1999-03-01 00:00:00.000 1999-03-01 00:00:00.000
4 3 2 864211 113523275 02 1999-03-01 00:00:00.000 1999-12-31 00:00:00.000
5 3 3 864212 113523275 01 1998-06-01 00:00:00.000 1999-12-31 00:00:00.000
6 2 3 864212 041609336 02 1998-05-01 00:00:00.000 1998-05-31 00:00:00.000
7 1 3 864212 091547708 03 1998-06-01 00:00:00.000 1998-06-01 00:00:00.000
8 2 4 867616 041609336 03 1998-05-01 00:00:00.000 1998-05-01 00:00:00.000
9 3 4 867616 113523275 03 1998-06-01 00:00:00.000 1999-12-31 00:00:00.000
10 4 5 054911 079548709 01 2012-08-01 00:00:00.000 9999-12-31 00:00:00.000
5. Customer table should look like below:
IndContractId and ContractID for this table comes from IndivuidialContract table.
CustomerID IndContractID ContractID MemberNo SubsNo PerNo
1 1 1 824212 091547708 01
1 2 4 824212 079548709 02
2 3 2 864211 041609336 01
2 4 3 864211 113523275 02
3 5 3 864212 113523275 01
3 6 2 864212 041609336 02
3 7 1 864212 091547708 03
4 8 2 867616 041609336 03
4 9 3 867616 113523275 03
5 10 4 054911 079548709 01Your DDL is wrong. No keys, NO way to have keys, singular table names (I am sorry you have only one customer), etc. You do not know the syntax for insertion, etc. You have no idea how to do a data model. Why is a party use a physical table property as an
identifier?? Did you know about the DATE data type?
Why did you use IDENTITY? Why is the count of physical insertions an attribute of a contract in your mind? This is as silly as identifying a car by the parking space number in one garage! But not the VIN.
CREATE TABLE Parties
(party_duns CHAR(9) NOT NULL PRIMARY KEY,
party_registration_date DATE DEFAULT CURRENT TIMESTAMP NOT NULL,
member_nbr CHAR(16) NOT NULL,
subs_nbr CHAR(9) NOT NULL,
per_nbr CHAR(2) NOT NULL NOT NULL);
Do you know what a DUNS is and why it is a valid identifier for a party in a contract?
CREATE TABLE Contracts
(contract_id CHAR(25) NOT NULL PRIMARY KEY,
party_duns CHAR(9) NOT NULL
REFERENCES Parties (party_duns),
member_nbr CHAR(16) NOT NULL,
subs_nbr CHAR(9) NOT NULL,
per_nbr CHAR(2) NOT NULL,
contract_start_date DATE DEFAULT CURRENT TIMESTAMP NOT NULL,
contract_end_date DATE,
CHECK (contract_start_date < contract_end_date));
Why did you put the DRI in a useless narrative?? I guessed at one.
CREATE TABLE Individual_Contracts
(ind_contract_id CHAR(25) NOT NULL,
contract_id CHAR(25) NOT NULL,
party_duns CHAR(9) NOT NULL,
member_nbr CHAR(16) NOT NULL,
subs_nbr CHAR(9) NOT NULL,
per_nbr CHAR(2) NOT NULL,
contract_start_date DATE DEFAULT CURRENT TIMESTAMP NOT NULL,
contract_end_date DATE)
CREATE TABLE Customers
( CustomerID int,
indcontract_id int,
contract_id CHAR(25) NOT NULL,
member_nbr CHAR(16) NOT NULL,
subs_nbr CHAR(9) NOT NULL,
per_nbr CHAR(2) NOT NULL)
>> The business Key is member_nbr, subs_nbr, per_nbr in all the 4 tables. <<
That is a design flaw. A key should locate one and only one entity in the schema. But you have split the entity over many tables.
>> Contract table has party_id as foreign Key from Parties table <<
Where is the DDL for this???
>> IndividualContract table has contract_id, party_id as foreignKeys from Parties table and Contract table. <<
Where is the DDL for this???
>> Customer table has Indcontract_id, contract_id as foreignKeys from IndividualContract table. <<
Where is the DDL for this???
>> CustomerID in Customer table is nothing but party_id. <<
Redundancy is the reason we moved from files to DBs.
>> IndividualContract and Customer tables should be one-one. <<
Where is the DDL for this???
You almost know what you are doing , which is a nice change from most postings here. But I cannot donate $$$$ hours of consulting to you. For example, why is an individual contract totally different form a mere contract? Etc.
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL -
Hi,
1. In the query below, How to display FirstActNum to the User( which is inner select decode statement ) ?
SELECT A.One, A.Two, A.Three, A.Four from
(Select FL.first_act_num as One,FL.move_num as Two, SUM (FL.payment) as Three,SUM(FL.next_amount) as Four from FirstLib FL
where FL.act_num IN (
Select
DECODE(l.first_act_num,'0000000',l.act_num,l.first_act_num) as FirstActNum
from FirstLib L, ManageAccount A
WHERE
L.act_id=A.act_id
AND A.id='123456789')
group by FL.primary_acct_num,FL.loan_num) A,OtherTable B
where A.One = B.first_act_num AND A.Two = B.move_num;
2. Is there any other better way to write these kind of queries?
ThanksSundar,
No, its different.. I am just comparing with that field.
The data looks like..
ACT_NUM FIRST_ACT_NUM
11111 11111
22222 11111
33333 11111
In some cases FIRST_ACT_NUM is not populated (i.e it will have 0000000), in this case I am using ACT_NUM
ACT_NUM FIRST_ACT_NUMM
55555 0000000
87878 0000000
90909 0000000 -
Sql Update Query help!!!..
Hi Guys,
below is the table , i am trying to update error_flg of records which have ID=2, NAME ='janice' to 2 if the error_flg is '0' and to '3' if the error flag is '1',
the bold are the records i want to update and i am also showing the result below in highlighted
CREATE TABLE person
ID NUMBER(12),
person_ID NUMBER(16),
NaME VARCHAR2(15 BYTE),
USERID VARCHAR2(7 BYTE),
error_flg VARCHAR2(1 BYTE)
insert into person (id,person_id,name,userid,error_flg) values(1,100,'micheal','userid','1')
insert into person (id,person_id,name,userid,error_flg) values(1,101,'steve','userid','1')
insert into person(id,person_id,name,userid,error_flg) values(1,102,'janice','userid','1')
insert into person (id,person_id,name,userid,error_flg) values(2,103,'janice','userid','1')
insert into person (id,person_id,name,userid,error_flg) values(2,104,'janice','userid','0')
insert into person (id,person_id,name,userid,error_flg) values(3,105,'janice','userid','0')
result should be:
insert into person (id,person_id,name,userid,error_flg) values(1,100,'micheal','userid','1')
insert into person (id,person_id,name,userid,error_flg) values(1,101,'steve','userid','1')
insert into person(id,person_id,name,userid,error_flg) values(1,102,'janice','userid','1')
insert into person (id,person_id,name,userid,error_flg) values(2,103,'janice','userid','3')
insert into person (id,person_id,name,userid,error_flg) values(2,104,'janice','userid','2')
insert into person (id,person_id,name,userid,error_flg) values(3,105,'janice','userid','0')
Edited by: oraclebeginner1231 on Jun 10, 2010 8:52 AMoraclebeginner1231 wrote:
that was smart..why did i not think .. also how to combine both?
thanks a lotYou can use a CASE statement to achieve that.
update person
set error_flg = case when error_flg = '0' then '2' when error_flg = '1' then '3' end
where id = 2
and name = 'janice'
and error_flg in ('0', '1'); -
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
Maybe you are looking for
-
Report Generation broken after deployment - Excel Set Cell Color and Border.vi
Upon deployment, the Excel Set Cell Color and Border.vi became broken. After installing LV2010 SP1 to view the VIs in the deployment, I noticed that in the second case structure where the code draws the border using the BorderAround invoke node, the
-
Standard report for SAP HR Infotype 8 India
Hi, I would like to know if SAP has provided standard report for infotype 8. 1) I would like to download personal no wise wage type data from infotype 8 for a period. 2) And I would like to compare the basic rate data prior to increment or promotion
-
I have made a mess of importing my photos from iphoto and wish to delete everything and start again with an empty Aperture - any ideas?
-
We would like to test old deltas from the source system( copied to new)
Hi Gurus, The scenario is They will make a DB copy of the Prod system onto a QA system, the Copied system will have its system ID changed(SID) to a new one. There will be deltas available in the RSA7, as this is a copy of the 3 weeks old prod system
-
Hi, I'm trying to insert an html snippet from vimeo but it doesn't work anymore (maybe since the latest OS update) All that I get is an empty frame... here's the embedding code: <iframe src="//player.vimeo.com/video/74010090?title=0&byline=0&portrait