Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
I have a patient table of one year. The columns are:VisitID/MRN/AdmitDate/DischargeDate/DRG/Princpx/prindxI need to count the number of visits within the past 30 days by visitid. For example..each patient has one MRN but each visit has a different visitid. 1234/30/jan1/jan4/344/33/454567/30/jan14/jan21/456/21/234533/30/mar23/mar30/345/34/44for encounter 4533 another column would place a '1', since he wasn't admitted 30 days prior. For 4567, the column would have 2, since he (4567 and 1234) were admitted within 30 days, etc. Hope that makes sense and appreciate any help.
sunitabeck
Master Smack Fu Yak Hacker
5155 Posts
Posted - 2012-08-15 : 17:14:31
If you are on SQL 2005 or later, you can use the APPLY operator:
SELECT a.*, b.VisitsWithin30DaysFROM PatientTable a OUTER APPLY ( SELECT COUNT(*) AS VisitsWithin30Days FROM PatientTable c WHERE c.MRN = a.MRN AND DATEDIFF(dd, c.AdmitDate,a.AdmitDate) BETWEEN 0 AND 30 ) b;