Skip to content

SQL Query get most recent activiy per account (efficient query)

I use MS SQL Server 2016 and try to query the MS Dynamics 2016 on-premise DB efficiently. You don’t need special knowledge about Dynamics to answer my problem because it’s rather an SQL but a CRM problem.

Suppose you have entities FilteredAccounts and FilteredActivities (that’s the name in Dynamics View)

FilteredActivites have the following columns:

FilteredActivites have the following columns:

What I am trying to achieve is a list of all Accounts which shows to each account the most recent completed activity.

I tried to get the most recent activities by:

Now how do I join FilteredAccounts and FilteredActivities efficiently so that per FilteredAccount row I just get the most recent FilteredActivity? Is the way I compute the most recent actitivity an efficient way of doing this`(i.e. > 1.000.000 rows for activities stored in the DB). Is there a better way of doing this (like triggering the script which stores the id of the most recent activityid on the account whenever an activity is added / changed. Would this harm the integrity of the CRM system? You don’t want to change the system db of your crm this way I suppose?

Advertisement

Answer

With the right indexes, cross apply might be the fastest approach:

The index you want is on FilteredActivites(regardingobjectid, accountid, actualend).

User contributions licensed under: CC BY-SA
7 People found this is helpful