tags:

views:

63

answers:

4

Hi, I have been trying to think of a way to retrieve some data from a database by way of a SQL query. I am trying to avoid doing it programatically.

essentially the source table is

ID,DateTime,Count

I want to get the sum of the count for a defined period of DateTime for each distinct ID within that period.

Any ideas people?

+2  A: 

Try something like this:

select ID, sum(Count)
from foo
where [DateTime] between @beginning and @end
group by ID;

This is assuming that you have two variables, @beginning and @end that are typed as DateTime.

Andrew Hare
Thanks so much. I wasn't aware of *group by*.
Matthew
Correct, but I wouldn't use BETWEEN because it is inclusive at both ends of the range. This means that if you stack ranges next to each other, you'll duplicate results the are exactly equal to the boundary conditions into 2 distinct outputs.
Craig Young
+2  A: 
you want a GROUP BY for this

select ID, sum(Count) as Sum
from yourTable
where DateTime between startDate and endDate
group by ID
dan
+1  A: 
SELECT ID, SUM(Count) 
FROM yourTable
WHERE DateTime => '2009-10-01' AND DateTime < '2009-11-01' 
GROUP BY ID;
Tjofras
+2  A: 

For dates, you should use >= and <, using the start of the period and the start of the next period, like this:

WHERE [DateTime] >= @StartPeriod AND [DateTime] < @StartNextPeriod

..making the whole thing:

SELECT ID, SUM(Count) AS Cnt
FROM dbo.someTable
WHERE [DateTime] >= @StartPeriod AND [DateTime] < @StartNextPeriod
GROUP BY ID;

Otherwise, you run the risk of missing something or including too much.

Rob Farley