I was selecting set of columns from difference table using union. Below is the sql script of MySQL. I need to select only the recent inserted records based on contactId and created_date.
SELECT contactId, created_date, riskRating_Flag, pep_Flag, remarks, tablename, action,screenid
FROM
(SELECT `contactId` AS contactId, `createdDate` AS created_date,
CASE
WHEN `riskRatingFlag`='1' THEN 'HIGH'
WHEN `riskRatingFlag`='0' THEN 'LOW'
ELSE NULL
END AS riskRating_Flag,
CASE
WHEN `pepFlag`='1' THEN 'YES'
WHEN `pepFlag`='0' THEN 'NO'
ELSE NULL
END AS pep_Flag,
`remarks` AS remarks,
'ResolveHit_T' AS `tablename`,
'Initiate Review' AS action,
`resolveHitId` AS screenid
FROM `ast_CustomersScreenedResolveHit_T`
UNION SELECT `contactId` AS contactId, `createdDate` AS created_date,
CASE
WHEN `riskRatingFlag`='1' THEN 'HIGH'
WHEN `riskRatingFlag`='0' THEN 'LOW'
ELSE NULL
END AS riskRating_Flag,
CASE
WHEN `pepFlag`='1' THEN 'YES'
WHEN `pepFlag`='0' THEN 'NO'
ELSE NULL
END AS pep_Flag,
`remarks` AS remarks,
'CountryRisk_T' AS `tablename`,
'Initiate Review' AS action,
`countryRiskId` AS screenid
FROM `ast_CustomersScreenedCountryRisk_T`
UNION SELECT `contactId` AS contactId, `createdDate` AS created_date,
CASE
WHEN `riskRatingFlag`='1' THEN 'HIGH'
WHEN `riskRatingFlag`='0' THEN 'LOW'
ELSE NULL
END AS riskRating_Flag,
CASE
WHEN `pepFlag`='1' THEN 'YES'
WHEN `pepFlag`='0' THEN 'NO'
ELSE NULL
END AS pep_Flag,
`remarks` AS remarks,
'OccupationRisk_T' AS `tablename`,
'Initiate Review' AS action,
`occupationRiskId` AS screenid
FROM `ast_CustomersScreenedOccupationRisk_T`) AS `result`
ORDER BY `result`.`created_date` DESC
The expected output is mentioned in the below image expected result
But the result I got is result what I got