Microsoft
Software
Hardware
Network
Question : Oracle 9i SQL decode
Hi,
I am trying write a SQL based on the following condition:
select
a.id,
a.col2 f_name,
b.col3 L-name,
c.v_date date_1,
decode(a.cat,'007','first'
,'008','se
cond','') as cat_type
.....
from a,b,c,...
where
......
The change I want to do on the above SQL is:
If the above SQL returns just one record for "first" and one for "second", I want to display only the record containing "first", this I can get by using MIN function in the decode, that is:
min(decode(a.cat,'007','fi
rst','008'
,'second',
'')) as cat_type, I will get just the record containing "first".
But, If it returns, more than one record for the "first" or "second" then it should return as it is.
For eg:
ID F_Name L_Name cat_type date_1
1 john smith first 02/01/2010
1 john smith first 14/04/2010
1 john smith second 05/03/2010
2 ..........................
.....
..........................
.....
..........................
.....
or
ID F_Name L_Name cat_type date_1
1 john smith first 02/14/2010
1 john smith second 04/16/2010
1 john smith second 02/19/2010
..........................
.....
..........................
.....
or
ID F_Name L_Name cat_type date_1
1 john smith first 02/17/2010
1 john smith first 01/19/2010
1 john smith second 03/20/2010
1 john smith second 02/28/2010
..........................
..........
..........
..........
......
..........................
.....
so on so forth..
I want to do something like:
(CASE WHEN ((a.cat = '007' AND COUNT(a.cat) > 1)
OR (a.cat = '008' AND COUNT(a.cat) > 1) ) THEN
decode(a.cat,'007','first'
,'008','se
cond','')
ELSE min(decode(a.cat,'007','fi
rst','008'
,'second',
'') )
END
) as cat_type
But this is not working properly..
Can somebody suggest a method to solve this?
Thanks@
Related Solutions:
Oracle SQL -- WHERE NOT CLAUSE
Answer : Oracle 9i SQL decode
to make it even more simple, all you need is the below i think. It produces same results as shown in the screenshat which i already attached.. we do not need addition group by etc..
Try this and choose which ever you want.
select *
from (
SELECT X.*,
COUNT(DECODE(X.C_TYPE, 'PRIMARY', 1, null)) OVER (PARTITION BY X.ID) PRIM_CNT,
COUNT(DECODE(X.C_TYPE, 'INITIAL', 1, null)) OVER (PARTITION BY X.ID) INIT_CNT
FROM
(SELECT T1.ID, T1.NAME, T1.DESCRP, t2.c_desc,
decode(T2.C_ID,'007','PRIM
ARY','008'
,'INITIAL'
,'') as C_TYPE
FROM TEST T1, TEST2 T2
WHERE
T1.ID = T2.ID
) X
group by x.ID, x.NAME, x.DESCRP, x.c_desc, x.C_TYPE ) A
where not ( a.prim_cnt =1 and a.init_cnt = 1 and c_type='PRIMARY' )
Thanks
Random Solutions
Problems sharing iTunes between accounts on a Mac
Online Forms and SQL
Repeating SQL
Adding Outlook Calendar entries from server
Guide to install OS in newly Hard Drive
Multiple repeat regions on 1 page with 1 recordset
How can you search e-mail within Outlook 2010 and not use the index?
pp0 IP configuration.
Outlook: Errors have been detected in the file
How do I delete all records from an ADODB recordset?