franglais
franglais

Reputation: 938

Getting the count of 2 different columns in one statement

I'm trying to get a count from 2 tables working and I'm struggling!

I've got a table with notebook items, a table with links to contacts, a table linking contacts to clients and a table linking clients to addresses. What I'm trying to do is find out how many times each postcode has been mailshotted grouped by contact and client.

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

But am, obviously, only getting the same count for both contacts and clients. I'm getting horrifically confused when trying to put it into nested select statements as I'm always getting errors, so would appreciate any help going!

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

Upvotes: 2

Views: 530

Answers (1)

Stephen Turner
Stephen Turner

Reputation: 7314

Count() will count all non null rows, as Andrew says you might be after: COUNT(DISTINCT thing) i.e.:

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

Then you will get two counts of the distinct values in each field.

I'm not sure this is what you want. You say:

What I'm trying to do is find out how many times each postcode has been mailshotted grouped by contact and client.

I'd expect to query the data like this:

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

To get:

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

Which is the count of mailshots 'for each postcode, contact and client' or 'grouped by postcode, contact and client'.

Upvotes: 1

Related Questions