I have following data
Table1
id col1 col2 col3
----------------------------------
1 abc 01/01/2012 -
1 abc 01/01/2012 A
2 abc 01/01/2012 -
2 abc 01/02/2012 -
3 abc 01/02/2012 -
3 xyz 01/01/2012 -
4 abc 01/02/2012 -
4 xyz 01/01/2012 -
4 xyz 01/02/2012 -
following is order to evaluate -
if(col1 is false) then evaluate col2 if(col2 is false) then col3:
Col1 - xyz has first preference from all values in this column
col2 - min date
col3 - not '-' or min(col3)
I want to return only one row for each id, if col1 fails go to col2, if this fails then go to col3 condition. From above table result should be
id col1 col2 col3
----------------------------------
1 abc 01/01/2012 A
2 abc 01/01/2012 -
3 xyz 01/01/2012 -
4 xyz 01/01/2012 -
I tried using dense rank but it didn't help. I'm not sure how to perform this logic using any available function or sql logic.
for col1 - if more than one row for same code or xyz code then fail
for col2 - if more than one row with same min date then fail
[use this only if col1 condition fails]
You can specify many conditions to order by in your analytic function
I'm assuming that you want
dense_rank
given that you used thedense_rank
tag. You don't talk about how you want to handle ties or whether ties are even possible, so it's not clear from the question itself whether you want to use therank
,dense_rank
, orrow_number
analytic functions. If you are only ever fetching the highest ranking row perid
,rank
anddense_rank
will behave identically and will return multiple rows if there are ties for first place.row_number
will always return a single row by arbitrarily breaking the tie. If you want to fetch rows other than the first row perid
, then you'll need to think about ties and you'll get different behavior fromrank
anddense_rank
. If two rows are tied for first,dense_rank
will assign the third row arnk
of 2 whilerank
will assign it arnk
of 3.This seems to work for the sample data you posted