Afternoon all,
I have a query here and to be perfectly honest it works (produces results) but i'm not sure it works properly...
Basically I have 2 tables, Customers which stores customer details & Customer_Contact which stores when customers are contacted with some notes.
CREATE TABLE [dbo].[Customers](
[C_ID] [int] NOT NULL,
[C_Name] [nvarchar](20) NOT NULL,
[C_Postcode] [nvarchar](20) NOT NULL,
[C_Status] [nvarchar](20) NOT NULL,
[C_Branch] [nvarchar](20) NOT NULL,
[C_Type] [nvarchar](20) NOT NULL,
);
INSERT INTO Customers(C_ID, C_Name, C_Postcode, C_Status, C_Branch, C_Type)
VALUES
('1000', 'John', 'AA1 1AA', 'Live', 'London', 'Sales'),
('1001', 'Jane', 'AA1 1AA', 'Live', 'London', 'Sales'),
('1002', 'Bob', 'AA1 1AA', 'Live', 'London', 'Sales')
;
CREATE TABLE [dbo].[Customer_Contact](
[CC_ID] [int] NOT NULL,
[CC_CustID] [int] NOT NULL,
[CC_Notes] [nvarchar](20) NOT NULL,
[CC_Date] [datetime2](3) NOT NULL
);
INSERT INTO Customer_Contact(CC_CustID, CC_Notes, CC_Date)
VALUES
('1000', 'Blar blar', '2023-02-01'),
('1000', 'Blar blar', '2022-11-21'),
('1000', 'Blar blar', '2022-11-18'),
('1001', 'Blar blar', '2022-10-22'),
('1001', 'Blar blar', '2022-10-15'),
('1002', 'Blar blar', '2022-10-15')
;
I'm looking to get any customers that havent been contacted in the last month & output they're data and the last date they were contacted. The Query I have is:
SELECT C_ID, C_Name, C_Postcode, C_Status, C_Branch, C_Type, MIN(CONVERT(date,CC_Date)) AS C_DateContacted
FROM Customers
JOIN Customer_Contact On C_ID = CC_CustID
WHERE C_ID NOT IN
(
SELECT CC_ID FROM Customer_Contact
WHERE CC_Date > DATEADD(Month, -1, CONVERT(date,getdate()))
)
AND (C_Status = 'Live')
GROUP BY C_ID, C_Name, C_Postcode, C_Status, C_Branch, C_Type
ORDER BY C_DateContacted DESC
Can anyone see any glaring errors or even a better way to achieve it?
Many thanks
Dave