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

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 List events per week (solved)

Author  Topic 

Ironic
Starting Member

3 Posts

Posted - 2012-11-25 : 03:27:07
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?

Regards

Luuk123
Yak Posting Veteran

52 Posts

Posted - 2012-11-25 : 07:07:36
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

39 Posts

Posted - 2012-11-25 : 08:32:18
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)
GROUP BY
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.
Go to Top of Page

Ironic
Starting Member

3 Posts

Posted - 2012-11-25 : 16:27:11
Tks for the tips. i got it now
Go to Top of Page
   

- Advertisement -