I have a (hopefully) little problem in SQL where I need to query back a single value from 3 columns in a new column.
Here is what my table looks like :
Name of the issuer #ofratings Agency1 Agency2 Agency3
AAA 3 22 22 24
BBB 3 22 24 28
CCC 2 16 12 NULL
DDD 2 16 16 NULL
EEE 1 NULL 3 NULL
Now my problem... I'll try to be has clear as possible feel free to tell me if I an unclear.
I need to create a new column where I would bring back the resulting agency value following these rules
- IF I have 3 agency quotes and none are identical, then I want the middle one (Issuer BBB in the example).
- If I have 3 agency quotes and 2 are identical then I want that one in the new column (Issuer AAA in the example.
- If I have 2 agency quotes and they are identical, then I want either to be brought back in my new column (Issuer DDD in the example).
- If I have 2 agency quotes and both are different then I want the minimum between the 2(Issuer CCC in the example).
- If I have only 1 agency quote then I want that one brought back (Issuer EEE in the example).
Mind you I can just has easily have agency 1 and 3 be identical in the Issuer AAA and so forth.
I did a search on getting the min values from 3 columns and got fou What's the best way to select the minimum value from several columns?
The problem is I tried the CASE WHEN THEN example given but SQL allows a maximum of 10 levels on nesting in a case argument and my rule makes me bust that :S
Any help would be greatly appreciated.
Thank you
EDIT for @Fabien the Solution
HEre is the Select function in question Mind you that S&P is Agency 1 in my example, Moodys is agency2 and DBRS is agency3
Select
no.issuer_cd,
count(distinct(no.Rater_CD)) as 'norating',
SP.rating_rank as 'S&P',
MO.rating_rank as 'Moodys',
DB.rating_rank as 'DBRS'
from csm_issuer_rating r
left join
(select
no.issuer_cd,
no.rater_cd
from csm_issuer_rating no
where no.rater_cd in ('M_SP_BOND','M_DBRS_BOND','M_MOODY_BOND')) as no
on r.issuer_cd = no.issuer_cd
left join
csm_issuer i on i.issuer_cd = no.issuer_cd
Left join
csm_rater_rating rr on rr.rater_cd = no.rater_cd
left join
( select
r.issuer_cd,
r.rating_cd,
rr.rating_rank
from csm_issuer_rating r
left join csm_rater_rating rr on rr.rating_cd = r.rating_cd
where rr.rater_cd = 'M_SP_BOND' and r.rater_cd = 'M_SP_BOND'
) as SP
on i.issuer_cd = sp.issuer_cd
left join
( select
r.issuer_cd,
r.rating_cd,
rr.rating_rank
from csm_issuer_rating r
left join csm_rater_rating rr on rr.rating_cd = r.rating_cd
where rr.rater_cd = 'M_MOODY_BOND' and r.rater_cd = 'M_MOODY_BOND'
) as MO
on i.issuer_cd = mo.issuer_cd
left join
( select
r.issuer_cd,
r.rating_cd,
rr.rating_rank
from csm_issuer_rating r
left join csm_rater_rating rr on rr.rating_cd = r.rating_cd
where rr.rater_cd = 'M_DBRS_BOND' and r.rater_cd = 'M_DBRS_BOND'
) as DB
on i.issuer_cd = db.issuer_cd
group by
no.issuer_cd,
SP.rating_rank,
MO.rating_rank,
DB.rating_rank)