Please start any new threads on our new site at We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 List events per week (solved)
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Starting Member

3 Posts

Posted - 11/25/2012 :  03:27:07  Show Profile  Reply with Quote
I have a list of events, each with a date.
What i want is to see how many events happened per week last year.

I think i can use BETWEEN two dates and COUNT number of events.
I was planning on GETDATE(), subtract a year, and add 0 to 51 weeks to get all the weeks. However i heard that loops are frowned upon in SQL.
Is there an alternative way of doing it?


Edited by - Ironic on 11/25/2012 16:27:55

Yak Posting Veteran

52 Posts

Posted - 11/25/2012 :  07:07:36  Show Profile  Reply with Quote
You can use the DATEPART function like this:

select count(*), Datepart(week , modifieddate)
From Production.Document
group by Datepart(week , modifieddate)
Go to Top of Page

Elizabeth B. Darcy
Starting Member

United Kingdom
39 Posts

Posted - 11/25/2012 :  08:32:18  Show Profile  Reply with Quote
If you want to restrict the query to one year, include a WHERE clause as shown below.
SELECT COUNT(*) AS NumberOfEvents,
       DATEPART(week, modifieddate) AS [WeekNumber]
FROM   Production.Document
WHERE modifieddate > CAST(DATEADD(yy,-1,GETDATE()) AS DATE)
       DATEPART(week, modifieddate)

One other thing I must mention is that the result you get would be dependent on the datefirst setting of the session where the query is run (which defaults to the datefirst setting of the server if not explicitly set). If that is a consideration, there are other ways to get the results in a consistent manner, but if it is not, forget that I even said this.

-- Yes, I am indeed a fictional character.

Edited by - Elizabeth B. Darcy on 11/25/2012 08:58:25
Go to Top of Page

Starting Member

3 Posts

Posted - 11/25/2012 :  16:27:11  Show Profile  Reply with Quote
Tks for the tips. i got it now
Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.03 seconds. Powered By: Snitz Forums 2000