amar_kaur16 (9/4/2015)
I have a table with appdt as first appointment date and the another record for the same customer# has follow up appointment.Each customer is uniquely identified by a customer#
I need to find out if the customer came back after 200 days or more when the first appointment date was between jan12014 and Aug 31 2014. I am only interested in first follow up appointment after 30 days or more.
How can i do that in a query?
Thanks,
Blyzzard
Since you are using SQL 2012, let's use some of the new features:
First put some test data into a table to run from. You really should have provided some test data for us in readily consumable format, like I did below. Please see the first link in my signature for how to do this.
DECLARE @Customers TABLE (
CustomerID INTEGER,
ApptDt DATE,
PRIMARY KEY (CustomerID, ApptDt)
);
INSERT INTO @Customers (CustomerID, ApptDt)
VALUES (1, '2014-05-01'),
(1, '2014-06-15'), -- 45 days between appts
(2, '2014-06-01'),
(2, '2014-06-28'),
(3, '2014-03-20'),
(3, '2014-10-25');
-- create some variables
DECLARE @StartDate DATE = '2014-01-01',
@EndDate DATE = '2014-08-31';
WITH cte AS
(
-- Get the customers and their first appointment within the specified date range.
SELECT CustomerID, MIN(ApptDt) AS FirstApptDt
FROM @Customers
WHERE ApptDt >= @StartDate AND ApptDt <= @EndDate
GROUP BY CustomerID
), cte2 AS
(
SELECT t2.CustomerID,
t2.FirstApptDt,
-- get the next appointment for this customer
LEAD(ApptDt, 1, NULL) OVER (PARTITION BY t1.CustomerID ORDER BY t1.ApptDt) AS NextApptDate,
-- get the row number for this row
ROW_NUMBER() OVER (PARTITION BY t1.CustomerID ORDER BY t1.ApptDt) AS RN
-- join the subquery to the table
FROM @Customers t1
JOIN cte t2
ON t1.CustomerID = t2.CustomerID
)
-- now add the number of days between the two dates,
-- and filter for just the first row and for appointments > 30 days.
SELECT cte2.CustomerID,
cte2.FirstApptDt,
cte2.NextApptDate,
ca.DaysBetweenAppts
FROM cte2
CROSS APPLY (VALUES (DATEDIFF(DAY, cte2.FirstApptDt, cte2.NextApptDate))) ca(DaysBetweenAppts)
WHERE RN = 1
AND ca.DaysBetweenAppts >= 30
Does this handle what you're looking for?
Wayne
Microsoft Certified Master: SQL Server 2008
Author - SQL Server T-SQL Recipes