1

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?

1
  • Thanks so much for the prompt help :) Commented Dec 9, 2009 at 23:56

4 Answers 4

3
you want a GROUP BY for this

select ID, sum(Count) as Sum
from yourTable
where DateTime between startDate and endDate
group by ID
Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

Thanks so much. I wasn't aware of group by.
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.
2

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.

Comments

1
SELECT ID, SUM(Count) 
FROM yourTable
WHERE DateTime => '2009-10-01' AND DateTime < '2009-11-01' 
GROUP BY ID;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.