Query to show last note added in problem request. (MSSQL & PGSQL)

Query to show last note added in problem request. (MSSQL & PGSQL)

Tested in Build PGSQL (14300) or MSSQL (14306)
Problem Request:

SELECT ad.ORG_NAME AS "Account", prob.PROBLEMID AS "Problem ID", statdef.STATUSNAME AS "Status", LONGTODATE(prob.REPORTEDTIME) AS "Reported Date", ownaaa.FIRST_NAME AS "Technician", priodef.PRIORITYNAME AS "Priority", prob.TITLE AS "Title", orgaaa.FIRST_NAME AS "Reported by",sdpnotes.description "Last notes added",  LONGTODATE(sdpnotes.recordeddate) "Last notes added date",notedaddedby.first_name "Last notes added by" FROM Problem prob 
LEFT JOIN SDUser orgsd ON prob.ORIGINATORID=orgsd.USERID 
LEFT JOIN AaaUser orgaaa ON orgsd.USERID=orgaaa.USER_ID 
LEFT JOIN SDUser ownsd ON prob.OWNERID=ownsd.USERID 
LEFT JOIN AaaUser ownaaa ON ownsd.USERID=ownaaa.USER_ID 
LEFT JOIN StatusDefinition statdef ON prob.STATUSID=statdef.STATUSID 
LEFT JOIN PriorityDefinition priodef ON prob.PRIORITYID=priodef.PRIORITYID 
INNER JOIN AccountSiteMapping asm ON prob.SITEID=asm.SITEID 
INNER JOIN AccountDefinition ad ON asm.ACCOUNTID=ad.ORG_ID
LEFT JOIN problemtonotes ptm on ptm.problemid=prob.problemid
LEFT JOIN sdpnotes on sdpnotes.notesid=ptm.notesid
LEFT JOIN aaauser notedaddedby on notedaddedby.user_id=sdpnotes.userid
where sdpnotes.notesid = (select max(problemtonotes.notesid) from problemtonotes where problemtonotes.problemid=ptm.problemid) or ptm.problemid is NULL

                  New to ADSelfService Plus?