CRM 如何在没有活动联系人的情况下查找帐户
CRM How to Find Account without Active Contacts
这应该很简单,但我很难理解。基本上找到所有没有活动联系人的帐户。所以所有有联系人的帐户都处于非活动状态,或者没有任何联系人的帐户。
我尝试了两种方法,一种是使用左连接的查询,一种是使用 'Not Exists' 的查询,但一直没有返回任何内容:
查询 1:
SELECT a.name, a.statecode AS AccountStatus, c.StateCode AS ContactStatus, c.FullName
FROM dbo.Account a
LEFT JOIN dbo.Contact c
ON a.AccountId = c.ParentCustomerId
AND c.statecode = 0 --active contacts
WHERE c.ContactId IS NULL
查询 2:
SELECT *
FROM dbo.Account a
WHERE accountid IN (Select accountid FROM Account)
AND NOT EXISTS
(Select c.ParentCustomerId FROM dbo.Contact c
WHERE c.StateCode = 0
AND c.ParentCustomerId IS NOT NULL)
您可以试试下面的查询
SELECT ac.accountid,ac.name
FROM account ac
LEFT JOIN contact ca
ON ac.accountid=ca.parentcustomerid
GROUP BY ac.accountid,ac.name
HAVING COUNT(DISTINCT ca.contactid)=0
OR SUM(CASE WHEN ca.statecode=0 THEN 1 ELSE 0 END)>0
您的要求转化为:
- 所有帐户
- 没有活跃的联系人
会翻译成
SELECT
*
FROM
dbo.Account a -- all accounts
WHERE
NOT EXISTS( -- for which no contact exists
SELECT
1
FROM
dbo.Contact c
WHERE
c.ParentCustomerId=a.AccountId AND
c.StateCode<>0 -- that is active
);
这应该很简单,但我很难理解。基本上找到所有没有活动联系人的帐户。所以所有有联系人的帐户都处于非活动状态,或者没有任何联系人的帐户。
我尝试了两种方法,一种是使用左连接的查询,一种是使用 'Not Exists' 的查询,但一直没有返回任何内容:
查询 1:
SELECT a.name, a.statecode AS AccountStatus, c.StateCode AS ContactStatus, c.FullName
FROM dbo.Account a
LEFT JOIN dbo.Contact c
ON a.AccountId = c.ParentCustomerId
AND c.statecode = 0 --active contacts
WHERE c.ContactId IS NULL
查询 2:
SELECT *
FROM dbo.Account a
WHERE accountid IN (Select accountid FROM Account)
AND NOT EXISTS
(Select c.ParentCustomerId FROM dbo.Contact c
WHERE c.StateCode = 0
AND c.ParentCustomerId IS NOT NULL)
您可以试试下面的查询
SELECT ac.accountid,ac.name
FROM account ac
LEFT JOIN contact ca
ON ac.accountid=ca.parentcustomerid
GROUP BY ac.accountid,ac.name
HAVING COUNT(DISTINCT ca.contactid)=0
OR SUM(CASE WHEN ca.statecode=0 THEN 1 ELSE 0 END)>0
您的要求转化为:
- 所有帐户
- 没有活跃的联系人
会翻译成
SELECT
*
FROM
dbo.Account a -- all accounts
WHERE
NOT EXISTS( -- for which no contact exists
SELECT
1
FROM
dbo.Contact c
WHERE
c.ParentCustomerId=a.AccountId AND
c.StateCode<>0 -- that is active
);