oracle, find duplicate in one column based on another - oracle

create table stest1(x number,y number);
insert into stest1 values(1,10);
insert into stest1 values(1,11);
insert into stest1 values(1,10);
insert into stest1 values(2,9);
insert into stest1 values(2,9);
insert into stest1 values(1,9);
commit;
I would like to know all the values in column x that have more than one values of y
so from above, 1 has more than one value stored in y (10,11 and 9) where as 2 has only one value which is 9, so the result of my query should give 1
how to write such a query ?

If all you are after is the x, we can self join like this:
select distinct s1.x
from stest1 s1
inner join stest1 s2
on s1.x = s2.x
and s1.y <> s2.y
EDIT:
To get both x and y, you could move the above into a CTE and then only select the existing x:
with dupes as
(
select distinct s1.x
from stest1 s1
inner join stest1 s2
on s1.x = s2.x
and s1.y <> s2.y
)
select stest1.*
from stest1
where stest1.x in (select x from dupes)

Related

add values from other table using cursor in oracle

I am trying to execute the following steps:
Let's say we have a table t1
CREATE TABLE t1 (i1 varchar2,d1 varchar2,l1 varchar2, h1 number(1),q1 number, s1 date );
insert into t1 values('123','1','123-1',0,0,sysdate);
insert into t1 values('123','1','234-1',0,0,sysdate+2);
insert into t1 values('456','2','345-1',0,0,sysdate);
insert into t1 values('456','2','456-1',0,0,sysdate+2);
CREATE TABLE t2 (i2 varchar2,d2 varchar2,q2 number,a2 date );
insert into t2 values('123','1','1230',sysdate);
insert into t2 values('123','1','2340',sysdate+1);
insert into t2 values('456','2','3450',sysdate);
insert into t2 values('456','2','4560',sysdate+1);
Now I have to order t1 data in ascending order of s1 for same i1 and d1 and then check with a2 column of t2. If a2>=s1 but a2< next greater value of s1 then add q2 and assign it to q1.
I am trying to write a cursor which will take values from t1 in ascending order of s1,
for t2.a2>=s1 and t2.a2<s2 --s2 is next greater date value of t1.s1 column
q1 = q1+q2;
I am unable to find an efficient way to do this.
my cursor is:
cursor c1 is (select * from(select i1,d1,s1,min(s1) from t1 where h1=0
group by i1,d1,s1 order by i1,d1,s1));
declare
v_s
v_i
v_d
v_s1
v1 date;
v_q number;
begin
open c1;
fetch c1 into v_i,v_d,v_s,v1;
loop
select s1 into v_s1
from t1 t
where t.i1 = v_i and t.d1=v_d and t.s1>v_s;
select sum(t2.q2) into v_q
from t2 t
where t2.i1=v_i and t2.d2=v_d and t2.a2>=v_s and t2.a2<v_s1;
update t1 set q1 = v_q;
end loop;
close c1;
end;
I want q1 to be populated with sum(q2) for all a2 dates if a2 falls between min and max(s1).
I am unable to execute this. I either keep getting no data found or too many rows fetched or some other error. How can I do this efficiently?
Since you have not shared the end result, I think you want rows 2 & 4 to be null for column Q1. You can try the below co-related sub query to achieve the desired result -
UPDATE t1
SET Q1 = (SELECT SUM(q2)
FROM (SELECT t2.*, a2 - lag(a2) over(partition by i2, d2 order by a2) date_diff
FROM t2) t2
WHERE t1.i1 = t2.i2
AND t1.d1 = t2.d2
AND t1.s1 <= t2.a2
AND NVL(date_diff, 1) = 1);
Demo.

Oracle delete from tableA where a duplicate row is in tableB

As the title says, I am looking for a way to remove all rows from TableA where there is a matching row in TableB.
the Tables A & B have about 30 columns in them so a WHERE A.col1 = B.col1 etc would be a little problematical. Ideally I was hoping for something like
DELETE FROM tableA WHERE IN TableB
(overly simplified by this type of thing)
IN clause can compare all columns returned from select
DELETE FROM tableA WHERE ( col1,col2,col3,.. ) IN ( select col1,col2,col3... FROM TableB );
The brute force way to establish if two records from each table are the same is to just compare every column:
DELETE
FROM tableA a
WHERE EXISTS (SELECT 1 FROM tableB b WHERE a.col1 = b.col1 AND a.col2 = b.col2 AND ...
a.col30 = b.col30);
You could create function which checks structures of tables and, if they are the same, creates string containing correct conditions to compare.
For example here are two tables:
create table t1 (id, name, age) as (
select 1, 'Tom', 67 from dual union all
select 2, 'Tia', 42 from dual union all
select 3, 'Bob', 16 from dual );
create table t2 (id, name, age) as (
select 1, 'Tom', 51 from dual union all
select 3, 'Bob', 16 from dual );
Now use function:
select generate_condition('T1', 'T2') from dual;
result:
T1.ID = T2.ID and T1.NAME = T2.NAME and T1.AGE = T2.AGE
Copy this, paste and run delete query:
delete from t1 where exists (select 1 from t2 where <<PASTE_HERE>>)
Here is the function, adjust it if needed. I used user_tab_columns so if tables are on different schemas you need all_tab_columns and compare owners too. If you have Oracle 11g you can replace loop with listagg(). Second table has to contain all columns of first table and they have to be same type and length.
create or replace function generate_condition(i_t1 in varchar2, i_t2 in varchar2)
return varchar2 is
v varchar2(1000) := '';
begin
for rec in (select column_name, u2.column_id
from user_tab_cols u1
left join (select * from user_tab_cols where table_name = i_t2) u2
using (column_name, data_type, data_length)
where u1.table_name = i_t1 order by u1.column_id)
loop
if rec.column_id is null then
v := 'ERR: incompatible structures';
goto end_loop;
end if;
v := v||' and '||i_t1||'.'||rec.column_name
||' = '||i_t2||'.'||rec.column_name;
end loop;
<< end_loop >>
return(ltrim(v, ' and '));
end;
If you want to avoid running process manually you need dynamic PL/SQL.
create table tableA (a NUMBER, b VARCHAR2(5), c INTEGER);
create table tableB (a NUMBER, b VARCHAR2(5), c INTEGER);
As you said
WHERE A.col1 = B.col1 etc would be a little problematical
you could intersect the tables and mention all columns from tableA one time, like this:
delete tableA
where (a,b,c) in (select * from tableA
intersect
select * from tableB);

How to Update value in one table by coping it from another table in plsql ?

This is a simple example of what I need to do. In fact I want to Update value in one table by coping it from another table by using cursors in plsql.
I take table f and table b as two examples:
f=
1|Thom
2|Bob
3|Steven
5|Arthur
b=
7|Nataly
9|Alfred
, where I need to insert the b 's tow lines in first f two lines:
create table f (a number, b varchar2(10));
insert into f values (1,'Thom');
insert into f values (2,'Bob');
insert into f values (3,'Steven');
insert into f values (5,'Arthur');
commit;
create table b (c number, d varchar2(10));
insert into b values (7,'Nataly');
insert into b values (9,'Alfred');
commit;
create or replace procedure wco as
cursor c_f is
select a,b from f for update;
v_a f.a%type;
v_b f.b%type;
cursor c_b is
select c,d from b;
v_c b.c%type;
v_d b.d%type;
begin
open c_f;
open c_b
loop
fetch c_f into v_a, v_b;
exit when c_f%ROWCOUNT=c_b%RROWCOUNT;
update f set a=v_c and b=v_d where current of c_f;
end loop;
close c_d:
close c_f;
end;
/
exec wco;
select * from f;
drop table f;
The expected result (What i hope to have):
7|Nataly
9|Alfred
3|Steven
5|Arthur
But what I have now (as a result)is:
1|Thom
2|Bob
3|Steven
5|Arthur
How do I resolve this problem, I am a beginner with PLSQL, I would be very grateful if you could help me please.
Your procedure compiles, but with errors;
In order to see compilation errors
run show errors; after compilation.
Change open c_b to open c_b; (missing semicolon at the end)
Change close c_d: to close c_b; (correct name is c_b and semicolon instead of colon)
Change exit when c_f%ROWCOUNT=c_b%RROWCOUNT; to exit when c_f%ROWCOUNT=c_b%ROWCOUNT; (wrong %RROWCOUNT;)
update f set a=v_c and b=v_d where current of c_f; This is wrong SQL syntax.
Should be update table_name set column=value, column=value;
It is important to provide descriptive names to your variables, so it would be easier to understand your logic.
As I understood you want to copy only second two rows from source table.
create table source_table (
id number,
name varchar2(10));
/
insert into source_table values (1,'Thom');
insert into source_table values (2,'Bob');
insert into source_table values (3,'Steven');
insert into source_table values (5,'Arthur');
/
create table target_table (
id number,
name varchar2(10));
/
insert into target_table values (7,'Nataly');
insert into target_table values (9,'Alfred');
/
create or replace procedure copy_tables
AS
begin
FOR source_row IN (select id, name
from source_table
offset 2 rows)
LOOP
insert into target_table
values(source_row.id, source_row.name);
END LOOP;
end;
/
exec copy_tables;
/
select id, name from target_table;
/
You don't need PL/SQL for this; it can be achieved in a single MERGE statement:
merge into f tgt
using (select coalesce(b1.id, f1.id) id,
coalesce(b1.name, f1.name) name,
f1.f_rowid
from (select id,
name,
rowid f_rowid,
row_number() over (order by id) rn
from f) f1
full outer join (select id,
name,
row_number() over (order by id) rn
from b) b1
on f1.rn = b1.rn) src
on (tgt.rowid = src.f_rowid)
when matched then
update set tgt.id = src.id,
tgt.name = src.name
where tgt.id != src.id
or tgt.name != src.name
when not matched then
insert (tgt.id, tgt.name)
values (src.id, src.name);
See https://livesql.oracle.com/apex/livesql/file/content_FBPR7YCLFVWO7NGDXTLSP1R97.html for the test details (two examples; the target table has more and has fewer rows than the source table).
If you need to, you could add the above insert into a procedure, e.g.:
create procedure populate_target_table as
begin
merge into f tgt
using (select coalesce(b1.id, f1.id) id,
coalesce(b1.name, f1.name) name,
f1.f_rowid
from (select id,
name,
rowid f_rowid,
row_number() over (order by id) rn
from f) f1
full outer join (select id,
name,
row_number() over (order by id) rn
from b) b1
on f1.rn = b1.rn) src
on (tgt.rowid = src.f_rowid)
when matched then
update set tgt.id = src.id,
tgt.name = src.name
where tgt.id != src.id
or tgt.name != src.name
when not matched then
insert (tgt.id, tgt.name)
values (src.id, src.name);
end;
/

Insert into select statement on the same table

I'm currently migrating data from legacy system to the current system.
I have this INSERT statement inside a stored procedure.
INSERT INTO TABLE_1
(PRIMARY_ID, SEQUENCE_ID, DESCR)
SELECT LEGACY_ID PRIMARY_ID
, (SELECT COUNT(*) + 1
FROM TABLE_1 T1
WHERE T1.PRIMARY_ID = L1.LEGACY_ID) SEQUENCE_ID
, L1.DESCR
FROM LEGACY_TABLE L1;
However, whenever I have multiple values of LEGACY_ID from LEGACY_TABLE, the query for the SEQUENCE_ID doesn't increment.
Why is this so? I can't seem to find any documentation on how the INSERT INTO SELECT statement works behind the scenes. I am guessing that it selects all the values from the table you are selecting and then inserts them simultaneously after, that's why it doesn't increment the COUNT(*) value?
What other workarounds can I do? I cannot create a SEQUENCE because the SEQUENCE_ID must be based on the number of PRIMARY_ID that are present. They are both primary ids.
Thanks in advance.
Yes, The SELECT will be executed FIRST and only then the INSERT happens.
A Simple PL/SQL block below, will be a simpler approach, though not efficient.
DECLARE
V_SEQUENCE_ID NUMBER;
V_COMMIT_LIMIT:= 20000;
V_ITEM_COUNT := 0;
BEGIN
FOR REC IN (SELECT LEGACY_ID,DESCR FROM LEGACY_TABLE)
LOOP
V_SEQUENCE_ID:= 0;
SELECT COUNT(*)+1 INTO V_SEQUENCE_ID FROM TABLE_1 T1
WHERE T1.PRIMARY_ID = REC.LEGACY_ID
INSERT INTO TABLE_1
(PRIMARY_ID, SEQUENCE_ID, DESCR)
VALUES
(REC.LEGACY_ID,V_SEQUENCE_ID,REC.DESCR);
V_ITEM_COUNT := V_ITEM_COUNT + 1;
IF(V_ITEM_COUNT >= V_COMMIT_LIMIT)
THEN
COMMIT;
V_ITEM_COUNT := 0;
END IF;
END LOOP;
COMMIT;
END;
/
EDIT: Using CTE:
WITH TABLE_1_PRIM_CT(PRIMARY_ID, SEQUENCE_ID) AS
(
SELECT L1.LEGACY_ID,COUNT(*)
FROM LEGACY_TABLE L1
LEFT OUTER JOIN TABLE_1 T1
ON(L1.LEGACY_ID = T1.PRIMARY_ID)
GROUP BY L1.LEGACY_ID
)
INSERT INTO TABLE_1
(SELECT L1.LEGACY_ID,
CTE.SEQUENCE_ID+ (ROW_NUMBER() OVER (PARTITION BY L1.LEGACY_ID ORDER BY null)),
L1.DESCR
FROM TABLE_1_PRIM_CT CTE, LEGACY_TABLE L1
WHERE L1.LEGACY_ID = CTE.PRIMARY_ID);
PS: With your Millions of Rows, this is going to create a temp table
of same size, during execution. Do Explain Plan before actual execution.

Oracle11g ORA-01403 No data found using Select Into

I am quite new to Oracle and I have an issue I have been struggelig With for some hours.
sample:
Create Table Accounts (Id number(10),Balance number(16,3), Status Varchar2(50),Owner_Id number(10));
Create Table Transactions (Id number(10),Amount number(16,3), Trxn_date date, Account_Id number(10));
Create Table Owner (Id number(10), Firstname varchar2(50),Lastname varchar2(50));
Insert Into Accounts(Id,Balance,Status,Owner_Id) Values (1,1000,'OPEN',10);
Insert Into Accounts(Id,Balance,Status,Owner_Id) Values (2,5000,'CLOSED',11);
Insert Into Accounts(Id,Balance,Status,Owner_Id) Values (3,1000,'OPEN',12);
Insert Into Accounts(Id,Balance,Status,Owner_Id) Values (4,5000,'CLOSED',13);
Insert Into Accounts(Id,Balance,Status,Owner_Id) Values (5,1000,'OPEN',14);
Insert Into Accounts(Id,Balance,Status,Owner_Id) Values (6,5000,'CLOSED',15);
Insert Into Accounts(Id,Balance,Status,Owner_Id) Values (7,1000,'OPEN',16);
Insert Into Accounts(Id,Balance,Status,Owner_Id) Values (8,5000,'CLOSED',17);
Insert Into Accounts(Id,Balance,Status,Owner_Id) Values (9,1000,'OPEN',18);
Insert Into Accounts(Id,Balance,Status,Owner_Id) Values (10,5000,'CLOSED',19);
Insert Into Accounts(Id,Balance,Status,Owner_Id) Values (11,1000,'OPEN',20);
Insert Into Accounts(Id,Balance,Status,Owner_Id) Values (12,5000,'CLOSED',21);
Insert Into Owner(Id,Firstname,Lastname) Values (10,'John','TEST1');
Insert Into Owner(Id,Firstname,Lastname) Values (11,'John','TEST2');
Insert Into Owner(Id,Firstname,Lastname) Values (10,'John','TEST3');
Insert Into Owner(Id,Firstname,Lastname) Values (11,'John','TEST4');
Insert Into Owner(Id,Firstname,Lastname) Values (10,'John','TEST5');
Insert Into Owner(Id,Firstname,Lastname) Values (11,'John','TEST6');
Insert Into Owner(Id,Firstname,Lastname) Values (10,'John','TEST7');
Insert Into Owner(Id,Firstname,Lastname) Values (11,'John','TEST8');
Insert Into Owner(Id,Firstname,Lastname) Values (10,'John','TEST9');
Insert Into Owner(Id,Firstname,Lastname) Values (11,'John','TEST10');
Insert Into Owner(Id,Firstname,Lastname) Values (10,'John','TEST11');
Insert Into Owner(Id,Firstname,Lastname) Values (11,'John','TEST12');
Insert Into Transactions(Id,Amount,Trxn_Date,Account_Id) Values (1,10,'02-FEB-2015',5);
Insert Into Transactions(Id,Amount,Trxn_Date,Account_Id) Values (2,10,'02-APR-2015',5);
Insert Into Transactions(Id,Amount,Trxn_Date,Account_Id) Values (3,10,'02-JUN-2015',5);
Insert Into Transactions(Id,Amount,Trxn_Date,Account_Id) Values (4,10,'02-AUG-2015',5);
Insert Into Transactions(Id,Amount,Trxn_Date,Account_Id) Values (5,10,'02-FEB-2015',2);
Insert Into Transactions(Id,Amount,Trxn_Date,Account_Id) Values (6,10,'02-APR-2015',2);
Insert Into Transactions(Id,Amount,Trxn_Date,Account_Id) Values (7,10,'02-JUN-2015',2);
Insert Into Transactions(Id,Amount,Trxn_Date,Account_Id) Values (8,10,'02-AUG-2015',2);
Data Check:
Select Unique(Account_Id) From Accounts A
Inner Join Owner B on B.ID=A.OWNER_ID
Inner Join Transactions I on I.ACCOUNT_ID=A.Id
Where I.Trxn_date Between '01-FEB-2015' and '01-JUL-2015'
And A.Status='CLOSED'
and A.Balance=5000;/*1 Row Returned*/
The Loop must exit at first Id returned
Declare
l_NewDate date:='01-FEB-2015';
l_OldDate date:='01-JUL-2015';
l_pID number(10);
Begin
For I in (Select Account_Id From Transactions
Where Trxn_date Between l_NewDate and l_OldDate)
Loop
Select Id Into l_pID From
(Select B.Id From Accounts A
Inner Join Owner B on A.Owner_Id = B.Id
Where A.Status = 'CLOSED' And A.Balance = 5000 And A.Id=I.Account_Id)
Where rownum < 2;
dbms_output.put_line(l_pID);
Exit;
End Loop;
End;
ORA-01403: No data found
ORA-06512: at line 12
I fail to understand why no data is found when the data check above clearly states otherwise.
Regards
J. Olsen
Like you say, your data check query:
Select Unique(Account_Id)
From Accounts A
Inner Join Owner B on B.ID=A.OWNER_ID
Inner Join Transactions I on I.ACCOUNT_ID=A.Id
Where I.Trxn_date Between '01-FEB-2015' and '01-JUL-2015'
And A.Status='CLOSED'
and A.Balance=5000;
... returns a single row with a single Account_Id value of 2.
But then, your PL/SQL code basically splits the logic in 2 queries. The query you loop on is:
Select Account_Id
From Transactions
Where Trxn_date Between '01-FEB-2015' and '01-JUL-2015'
And, when I run it, it returns:
5
5
5
2
2
2
Now the above's order is not guaranteed, as you don't have an ORDER BY clause. But if you get the results in the same order as me, then your first loop iteration will execute the next query using 5 as input:
Select *
From Accounts A
Inner Join Owner B on A.Owner_Id = B.Id
Where A.Status = 'CLOSED'
And A.Balance = 5000
And A.Id = 5
... which doesn't return any data, which is why you get your error.
If you would have been lucky enough to have started with the value of 2:
Select *
From Accounts A
Inner Join Owner B on A.Owner_Id = B.Id
Where A.Status = 'CLOSED'
And A.Balance = 5000
And A.Id = 2
... it would have worked as expected.
I wish I could recommend a proper solution, but I just don't truly understand what you are trying to do. But it certainly feels like you shouldn't need PL/SQL loops to do what you want. A simple query should be sufficient. Your data check query seems like a good start.
EDIT
For what it's worth, I think this is a more straight forward way of doing the exact same thing you are intending to do (no loops):
Declare
l_NewDate date:='01-FEB-2015';
l_OldDate date:='01-JUL-2015';
l_pID number(10);
Begin
select o.id into l_pID
from transactions t
join accounts a
on a.id = t.account_id
and a.status = 'CLOSED'
and a.balance = 5000
join owner o
on o.id = a.owner_id
where t.trxn_date between l_NewDate and l_OldDate
and rownum < 2;
dbms_output.put_line(l_pID);
End;

Resources