views:

35

answers:

3

I am trying to figure out how to compare the current day's data to the same data from a week ago, 2 weeks, etc. Let's say I have a table called "Order" with 2 columns:

Order table
-----------
OrderID int identity
OrderDate datetime

If today, is Monday, I would like to be able to compare the number of orders from today to the previous Mondays for an entire year. Is this possible with a single SQL Server query? I'm using SQL 2008 if it makes a difference.

+1  A: 

Try

SELECT [ColumnsYouWant]
FROM [OrderTable]
WHERE datepart(weekday, OrderDate) = datepart(weekday, getdate()) 
   AND OrderDate >= dateadd(yyyy, -1, getdate())
LittleBobbyTables
+1  A: 
select CAST (OrderDate  as date) as [Date], COUNT(*)
from Orders
where OrderDate  > DATEADD(YEAR,-1, getdate()) 
     and DATEPART(DW,OrderDate ) = DATEPART(DW,GETDATE())
group by CAST (OrderDate  as date)
Martin Smith
Very nice - thanks!
Jason
+1  A: 

This gives you Monday order counts by week number:

select year(OrderDate) as Year, 
    DATEPART(WEEK, OrderDate) as Week, 
    COUNT(*) as MondayOrderCount
from Order
where DATEPART(WEEKDAY, OrderDate) = 2
group by year(OrderDate), DATEPART(WEEK, OrderDate)
order by Year, Week
RedFilter