I've got a SQL table (Email_Campaigns) with a master list of campaigns we've run:
Name DateSent
Campaign01 01/01/2011
Campaign02 01/15/2011
..
Campaign40 10/01/2011
I've got a list of customers (Email_Received) with their membership numbers and the campaigns they've received:
PK 开发者_C百科MembershipNo CampaignName
1 123456 Campaign01
2 123456 Campaign02
3 987654 Campaign05
4 111111 Campaign10
I've also got a master list of customer MembershipNo's (Customers)
Question: How do I write a query to list each campaign and count the number of customers who DID NOT receive that e-mail? For example ('Received' column is only shown here for reference and isn't imperative as I know how to calculate that):
Name Received DidNotReceive
Campaign01 1000 9000
Campaign02 3000 7000
..
Campaign40 100 9900
Here's one standard SQL way to write this:
SELECT ec.Name, count(c.MembershipNo) AS DidNotReceive
FROM Customers AS c
, Email_Campaigns AS ec
WHERE NOT EXISTS (
SELECT 1
FROM Email_Received AS r
WHERE er.CampaignName = ec.CampaignName
AND er.MembershipNo = c.MembershipNo)
GROUP BY ec.Name
ORDER BY ec.Name;
SELECT er.CampaignName,
COUNT(*) AS Received,
(SELECT COUNT(*) FROM Customers) - COUNT(*) AS DidNotReceive
FROM Email_Received er
GROUP BY er.CampaignName
ORDER BY er.CampaignName;
This is at the very simplest level. There are probably additional considerations to take into account, such as whether or not a given customer was active at the time the campaign was distributed.
精彩评论