2

我正在尝试从 2 个工作表中计数,但我很挣扎!

我有一个包含笔记本项目的表格、一个包含联系人链接的表格、一个将联系人链接到客户的表格以及一个将客户链接到地址的表格。我要做的是找出每个邮政编码按联系人和客户分组的邮件发送次数。

Postcode | Count of Clients | Count of Contacts    
UB | 123 | 12345    
HA | 223 | 22345

但是,显然,联系人和客户的数量相同。尝试将其放入嵌套选择语句中时,我感到非常困惑,因为我总是遇到错误,因此不胜感激!

select COUNT (ni.NotebookItemId) AS Clients, 
COUNT(nl.ObjectId) AS Contacts, 
Substring(ad.PostCode, 1, 2) AS Postcode
from NotebookItems ni
inner join notebooklinks nl on ni.NotebookItemId = nl.NotebookItemId
inner join ClientContacts cc on cc.ContactPersonId = nl.ObjectId
inner join address ad on ad.ObjectId = cc.ClientId
where NotebookTypeId = 75 AND ni.CreatedOn > 'mar 16 2012' 
AND (ad.postcode like 'UB%' or 
     ad.postcode like 'HA%')
GROUP BY Substring(ad.PostCode, 1, 2)
order by Contacts desc
4

1 回答 1

1

Count() 将计算所有非空行,正如安德鲁所说,您可能会追求:COUNT(DISTINCT thing)即:

select COUNT (DISTINCT ni.NotebookItemId) AS Clients, 
COUNT(DISTINCT nl.ObjectId) AS Contacts, 
Substring(ad.PostCode, 1, 2) AS Postcode
...

然后,您将获得每个字段中不同值的两个计数。

我不确定这是你想要的。你说:

我要做的是找出每个邮政编码按联系人和客户分组的邮件发送次数。

我希望像这样查询数据:

SELECT 
      Count(MailshotID) AS Count
    , Substring(address.PostCode, 1, 2) AS Postcode
    , ContactID
    , ClientID
FROM
    -- your joined tables here
WHERE
    -- your criteria here
GROUP BY 
      Substring(address.PostCode, 1, 2)
    , ContactID
    , ClientID

要得到:

Count   Postcode   ContactID  ClientID
3       UB         201        301
6       HA         202        302
2       UB         203        305
18      UB         203        306

这是“每个邮政编码、联系人和客户”或“按邮政编码、联系人和客户分组”的邮件数量。

于 2012-05-17T14:29:57.580 回答