I've a requirement where I need to fetch users latest 5 remarks
data including his User ID
.
So, I've used cross apply
and used RemarksData as alias
name.
SQL Query:
select DD.DEBTOR_ID,RemarksData.*
from DMS_DEBTOR DD
cross APPLY
(
SELECT TOP 5 DF.REMARK as [Remarks]
FROM DMS_FOLLOWUP DF
WHERE DF.DEBTOR_ID = DD.DEBTOR_ID
ORDER BY DF.FOLLOWUP_TIME desc
) RemarksData where DD.BATCHNO in ('MBB EX-24') and DD.flagabort='0' order by DD.NAME
My Query Sample Data:
ID NAME Remarks
-----------------------------------------
2881173 ARIFFIN Sent To FV
2881173 ARIFFIN CHECKING PAYMENT
2881173 ARIFFIN FULLSETTLEMENT
2881173 ARIFFIN CALLED BV
2881173 ARIFFIN BROKEN PROMISE
-----------------------------------------
1682126 ASRI Waiting For Results
1682126 ASRI CHECKING PAYMENT
1682126 ASRI PROPOSAL
1682126 ASRI CALLED
1682126 ASRI BROKEN PROMISE
-------------------------------------------
1703446 ASRUL Sent To FV
1703446 ASRUL CHECKING PAYMENT
1703446 ASRUL PROPOSAL
1703446 ASRUL RNR
1703446 ASRUL BROKEN PROMISE
For clear understanding, I've separated each user records.
Here as you can see, that query gives out every user with his last 5 remarks.
Now, I'm planning to convert the same query to MySQL but unable to find the alternative of cross Apply.
Can anyone suggest me, if this SQL query can be done in any other way or at least convert it to MySQL.
I've tried some online converters also but nothing worked for me.
I can provide additional information if needed.
MySQL Query which I've tried is :
SELECT
DD.DEBTOR_ID,DD.CARDNO,DD.ACCOUNTNO,DD.NAME,
,(SELECT DF.REMARK as Remarks
FROM DMS_FOLLOWUP DF
WHERE DF.DEBTOR_ID = DD.DEBTOR_ID
ORDER BY DF.FOLLOWUP_TIME DESC
LIMIT 1
) AS VALUE
FROM
DMS_DEBTOR DD limit 10;
But it is returning only 1 record for every debtor(user) here. But I need the latest 5 records. If I put the LIMIT 5
, then I'm getting an issue.