| Compare values based on range [message #643970] |
Sat, 24 October 2015 07:12  |
 |
rohit_shinez
Messages: 139 Registered: January 2015
|
Senior Member |
|
|
Hi,
I am having below tables
T1
ID Balance
1 500
2 50
3 1000
T2
Min Max Int
0 100 2
101 500 1
501 1000 3
Output required
ID R1 R2 R3 R1_int R2_int R3_int
1 0 500 0 0 1 0
2 50 0 0 2 0 0
3 0 0 1000 0 0 3
i need to check balance falling in which range and take the respective R1_int
for Eg. 500 falls between second range (R2)i.e 101-500 and take the int value which is 1 and place the value as R2_int(second range int value) with rest of R1_int and R3_int as zero
ID R1 R2 R3 R1_int R2_int R3_int
1 0 500 0 0 1 0
create table T1(id number,balance number);
create table T2(min number,max number,int number);
insert into T1
select 1,500 from dual
union all
select 2,50 from dual
union all
select 3,1000 from dual;
insert into T2
select 0,100,2 from dual
union all
select 101,500,1 from dual
union all
select 501,1000,3 from dual;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| Re: Compare values based on range [message #644009 is a reply to message #644005] |
Sun, 25 October 2015 13:28  |
 |
Michel Cadot
Messages: 68776 Registered: March 2007 Location: Saint-Maur, France, https...
|
Senior Member Account Moderator |
|
|
You will never be able to do it so I give you but this is the last time I try to help you.
You should envisage to either take courses on algorithm, RBDMS and SQL or change your job to no more encounter SQL.
SQL> select t1.id,
2 max(case when t2.id = 1 and t1.balance between t2.min and t2.max then t1.balance else 0 end) r1,
3 max(case when t2.id = 2 and t1.balance between t2.min and t2.max then t1.balance else 0 end) r2,
4 max(case when t2.id = 3 and t1.balance between t2.min and t2.max then t1.balance else 0 end) r3,
5 max(case when t2.id = 1 and t1.balance between t2.min and t2.max then t2.int else 0 end) r1_int,
6 max(case when t2.id = 2 and t1.balance between t2.min and t2.max then t2.int else 0 end) r2_int,
7 max(case when t2.id = 3 and t1.balance between t2.min and t2.max then t2.int else 0 end) r3_int
8 from t1, ( select t2.*, row_number() over (order by min) id from t2 ) t2
9 group by t1.id
10 order by t1.id
11 /
ID R1 R2 R3 R1_INT R2_INT R3_INT
---------- ---------- ---------- ---------- ---------- ---------- ----------
1 0 500 0 0 1 0
2 50 0 0 2 0 0
3 0 0 1000 0 0 3
|
|
|
|