Let's say I have a table "items", with a schema like this:create table items ( i INT IDENTITY(1,1) PRIMARY KEY CLUSTERED, i_users INT NOT NULL, datetime SMALLDATETIME NOT NULL DEFAULT(GETDATE())) )
Say I want to report on how many entries there are per i_users on a daily, weekly, and monthly basis.Right now, I have an ASP page which looks something like this pseudocode:szSQL="select distinct i_users from items order by i_users desc"Set oRS=oDB.Execute(szSQL)Do while not oRS.EOF iUsers=CLng(oRS("i_users")) szSQL2="select count(*) as x from items where i_users=" & iUsers & " and datetime>=dateadd(hour,-24,getdate())" Set oQS=oDB.execute(szSQL2) iDaily=CLng(oQS("x")) szSQL2="select count(*) as x from items where i_users=" & iUsers & " and datetime>=dateadd(hour,-168,getdate())" Set oQS=oDB.execute(szSQL2) iWeekly=CLng(oQS("x")) szSQL2="select count(*) as x from items where i_users=" & iUsers & " and datetime>=dateadd(hour,-720,getdate())" Set oQS=oDB.execute(szSQL2) iMonthly=CLng(oQS("x")) Response.Write("User: " & iUsers & ", " & iDaily & "," & iWeekly & "," & iMonthly & vbCrLF oRs.MoveNextLoop...it works, it it causes 4 select queries per record. The is a nonclustered index on the [datetime] field, so it's not horrendously expensive, but still, it feels pretty inefficient.Is there a way to rewrite that into a single query that will return the daily, weekly, and monthly values? Cheers-bEdited by - aiken on 07/27/2002 06:29:23