The source is a rating table which contains rating and rating date for an organization. Sample data is as below
In the target we have rating table which must have organization, ratings, rating date as a single record (i.e converting rows to columns ). Target looks like below
Below is the SQL Analytic query used
SELECT RATED_ASSESSABLE_OBJECT_ID,
rate1,
date1,
rate2,
date2,
rate3,
date3,
rate4,
date4
FROM (SELECT RATED_ASSESSABLE_OBJECT_ID as RATED_ASSESSABLE_OBJECT_ID,
rating_sYMBOL_CODE AS RATE1,
LEAD(rating_sYMBOL_CODE,1) OVER (PARTITION BY RATED_ASSESSABLE_OBJECT_ID ORDER BY RATING_EFFECTIVE_DATE) AS rate2,
LEAD(rating_sYMBOL_CODE,2) OVER (PARTITION BY RATED_ASSESSABLE_OBJECT_ID ORDER BY RATING_EFFECTIVE_DATE) AS rate3,
LEAD(rating_sYMBOL_CODE,3) OVER (PARTITION BY RATED_ASSESSABLE_OBJECT_ID ORDER BY RATING_EFFECTIVE_DATE) AS rate4,
RATING_EFFECTIVE_DATE AS daTE1,
LEAD(RATING_EFFECTIVE_DATE,1) OVER (PARTITION BY RATED_ASSESSABLE_OBJECT_ID ORDER BY RATING_EFFECTIVE_DATE) AS DATE2,
LEAD(RATING_EFFECTIVE_DATE,2) OVER (PARTITION BY RATED_ASSESSABLE_OBJECT_ID ORDER BY RATING_EFFECTIVE_DATE) AS Date3,
LEAD(RATING_EFFECTIVE_DATE,3) OVER (PARTITION BY RATED_ASSESSABLE_OBJECT_ID ORDER BY RATING_EFFECTIVE_DATE) AS Date4,
ROW_NUMBER() OVER(PARTITION BY RATED_ASSESSABLE_OBJECT_ID ORDER BY RATING_EFFECTIVE_DATE) AS ROW_NUMBER
FROM DERIVED_RATING_EVENT)
WHERE ROW_NUMBER = 1
ORDER BY RATED_ASSESSABLE_OBJECT_ID
Can this be done with JOINs functions? It's something I've been working on mastering in my academy.vertabelo.com basic SQL course, so I cannot really understand the mothod given here yet, but at least I can grasp the problem...
ReplyDelete