Query to find companies with no communication in the future

Hello fellow partners,

I have created a user view in Sage CRM on the company entity.

I need a list of companies that do not have any future communications so we can follow up with them. I think the view works but it is very slow and to go from 1 page of data to the other it is taking 4 minutes. Can you please tell me what I am doing wrong or if there is a better way of doing this or optimizing this query?

Thank you

CREATE VIEW vNoCommCurrent
AS
SELECT
DISTINCT vCompany.Comp_Name,
vCompany.Comp_CompanyId

FROM dbo.vCompany
INNER JOIN dbo.vCommunication ON dbo.vCommunication.CmLi_Comm_CompanyID = dbo.vCompany.Comp_CompanyId

WHERE dbo.vCommunication.CmLi_Comm_CompanyID is not null and dbo.vCompany.Comp_Deleted is null
and dbo.vCompany.comp_type IN ('CUSTOMER','LEAD') AND dbo.vCompany.Comp_Status = 'ACTIVE' AND dbo.vCompany.comp_grptype IN ('CUST','LEAD') AND

NOT EXISTS
(SELECT dbo.vCommunication.comm_datetime FROM dbo.vCommunication WHERE dbo.vCommunication.comm_datetime >= CONVERT(VARCHAR(11),GETDATE(),106) AND dbo.vCommunication.CmLi_Comm_CompanyID = dbo.vCompany.Comp_CompanyId)

  • 0

    A couple of things, firstly you could try adding the "NOLOCK" table hint, which is faster at reading data.

    Also, in your main query, you do NOT need to join with vCommunication. The NOT EXISTS statement takes there of this join.

    an optimised version would be like this....

    SELECT DISTINCT

    Comp_Name,

    Comp_CompanyId

    FROM

    Company with(nolock)

    WHERE

    Comp_Deleted IS NULL

    AND comp_type IN ('CUSTOMER','LEAD')

    AND Comp_Status = 'ACTIVE'

    AND comp_grptype IN ('CUST','LEAD')

    AND NOT EXISTS (

    SELECT comm_datetime

    FROM vCommunication with(nolock)

    WHERE

    comm_datetime >= CONVERT(VARCHAR(11),GETDATE(),106)

    AND CmLi_Comm_CompanyID = Comp_CompanyId

    )

  • 0

    Or Try this one - companies with no communications at all, or no pending communications within the last 90 days.

    SELECT Company.*,LastComm.lastdate

    FROM company

    LEFT OUTER JOIN (SELECT cmli_comm_companyid ,Max(comm_datetime) LastDate

    FROM communication

    JOIN Comm_Link ON CmLi_Comm_CommunicationId = Comm_CommunicationId

    WHERE comm_deleted IS NULL AND comm_status = 'Pending'

    GROUP BY cmli_comm_companyid) AS LastComm ON comp_companyid = cmli_comm_companyid

    WHERE comp_type IN ('Customer', 'Prospect')

    AND (LastComm.lastdate

    AND Comp_Deleted IS NULL

  • 0

    Thank you Kieron! I will give that a whirl.