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 Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Calculation that spans rows (probably non-aggregate)

Status
Not open for further replies.

jararaca

Programmer
Jun 1, 2005
159
US
Hi,

I have a table with a column called AdmitDate and I need to know how many rows in that table have AdmitDates that are within 30 days of the AdmitDate of the previous row. I'm stumped about how to write such a query, or if it is even possible to do so. Can anyone please help?

thanks
 
I usually use a table variable with an identity column to do this. Ex:

Code:
[green]-- Dummy data[/green]
Declare @YourTable Table(Id integer, AdmitDate DateTime)

Insert into @YourTable Values(1, '2006-06-28')
Insert into @YourTable Values(2, '2004-06-28')
Insert into @YourTable Values(2, '2005-06-28')
Insert into @YourTable Values(2, '2006-06-28')
Insert into @YourTable Values(3, '2006-06-01')
Insert into @YourTable Values(3, '2006-06-10')
Insert into @YourTable Values(3, '2006-06-28')

[green]-- End of dummy data
-- Query starts here[/green]

Declare @Temp Table (RowId Integer Identity(1,1), Id Integer, AdmitDate DateTime)

Insert Into @Temp(Id, AdmitDate)
Select Id, AdmitDate
From   @YourTable
Order By Id, Admitdate

Select *
From   @Temp A
       Inner Join @Temp B
         On  A.RowId = B.RowId - 1
         And A.ID = B.Id
         And DateDiff(dd, A.AdmitDate, B.AdmitDate) <= 30

Of course, tablenames and field names would have to change to match your database structure.

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top