在一个语句中计算2个不同的列

时间:2012-05-16 16:00:17

标签: sql-server-2008 tsql count

我正试图从两张桌子上算一下,我正在努力!

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

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

但显然,我只是为联系人和客户提供相同的数量。当我试图将它放入嵌套的select语句中时,我会感到非常困惑,因为我总是会遇到错误,所以非常感谢任何帮助!

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

1 个答案:

答案 0 :(得分: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

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