Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Count if an event occured each day of the year from date ranges 1

Status
Not open for further replies.

waubain

Technical User
Dec 13, 2011
200
0
0
US
Using prescription data and I am trying to count if a person had the opportunity to take at least 1 pill on each day of a period of interest, which in my current project is 365 days starting from an index date. I found this Example and spent several hours dissecting it, but it is beyond my understanding level. I am not interested in the max counts per interval, but I would just count the intervals where the count <> 0.
Our db has a dimDate table and has a DateID column and a date column smalldatetime

Here is some hypothetical prescription data

SQL:
DECLARE @StudyStartDate date = '2010-01-01' --inclusive
DECLARE @StudyEndDate date = '2011-01-01' --exclusive
CREATE TABLE #temp (PatientID int, RxFillID int, DrugID int, RxFillDate date, DaysSupply int)
INSERT INTO #temp VALUES
 (1,1,1001,'2010-01-01',30)
,(1,2,1001,'2010-03-01',30)
,(1,3,1001,'2010-05-01',30)
,(1,4,1001,'2010-07-01',30)
,(1,5,1001,'2010-09-01',30)
,(1,1,1002,'2010-04-01',30)
,(1,2,1002,'2010-06-01',30)
,(1,3,1002,'2010-08-01',30)
,(1,4,1002,'2010-10-01',30)
,(2,1,1003,'2010-01-01',90)
,(2,2,1003,'2010-05-01',60)
,(2,1,1004,'2010-05-01',90)

In the above example, patient#1 the two prescriptions never overlap, so that PrescriptionDay count would be 270, but patient #2 has prescriptions overlap so the opportunity on the overlapping days of the different prescriptions is still a 1, so the patients PrescriptionDay count would be 180. I hope that makes sense. The EndDate for each prescription fill would be DATEADD(d, [DaysSupply], [RxFillDate].

I may be looking through several million records. I do not have permissions in the db I am working to create a function or procedure.

I would appreciate any guidance, I am at a loss on where to start. Thank you in advance.

You don't know what you don't know...
 

SELECT t.PatientID, COUNT(DISTINCT d.CalendarDate)
FROM Dates d
JOIN #Temp t
ON d.CalendarDate BETWEEN t.RxFillDate AND DATEADD(DAY,t.DaysSupply -1,t.RXFillDate)
WHERE d.CalendarDate >= @StudyStartDate
AND d.CalendarDate < @StudyEndDate
GROUP BY t.PatientID
 
mharroff,
This is exactly what I was looking for in a much smaller package than what I was expecting based on the example.
Thank you very much for the prompt response and your expertise.

You don't know what you don't know...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top