I am trying to work out the difference between customers that have been billed in the last 3 months and the whole customer base. I have been able to calculate the customers that have been billed using the following SQL
DECLARE @DateFrom AS DATETIME
SET @DateFrom =
CONVERT(DATETIME, CAST(YEAR(GETDATE()) AS VARCHAR(4)) +
'-' +
CAST(MONTH(DATEADD(MONTH, -3, GETDATE())) AS VARCHAR(2)) + '-01', 120)
DECLARE @DateTo AS DATETIME
SET @DateTo =
CONVERT(DATETIME, CAST(YEAR(GETDATE()) AS VARCHAR(4)) +
'-' +
CAST(MONTH(GETDATE()) AS VARCHAR(2)) + '-01', 120)
SELECT DISTINCT
i.CustomerCode
FROM
Invoice AS i
WHERE
(i.InvoiceDate > @DateFrom AND i.InvoiceDate < @DateTo)
The table that I will be comparing against will be the Customer table which also has a CustomerCode field.
Thanks in advanced!
EDIT
After spending ages trying to figure this out and just after a few minutes of posting this message here I found a solution. Using the NOT IN clause!
SELECT
c.CustomerCode
FROM
[Customer] AS c
WHERE
c.CustomerCode NOT IN (
SELECT DISTINCT
i.CustomerCode
FROM
[Invoice] AS i
WHERE
(i.InvoiceDate >= @DateFrom AND i.InvoiceDate < @DateTo))
In my senario this appears to perform quicker then the steps mentioned below when I tested each in Management Studio.