SQL get Monthly, and weekly data

dateadddatediffsqlsql-date-functionssql-server-2008

I am writing a query to give me number of products sold this week, this month and this year (3 separate columns) on a week to date, month to date and year to date scale meaning today for example it will show products sold since monday, since the first of the month and since first of the year and this is to continue with each following week, month and year as time goes, there also are to be 3 other columns with the same logic for last year. What i need is help getting the date query using DATEADD or DATEDIFF (example (DATEADD(minute, -15, GETDATE())).

thank you very much and also i'm using SQL Server 2008

Best Answer

Here is some untested code which could probably be optimized, but should get you going in the right direction. This uses a PIVOT operation to transform your rows into columns.

SELECT WeekCount, MonthCount, YearCount
FROM
(
SELECT ProductId, 
    CASE
        WHEN ProductSoldDate >= DATEADD(dd, 1 - DATEPART(dw, GETDATE()), GETDATE())
        THEN 'WeekCount'
        WHEN ProductSoldDate >= DATEADD(mm, DATEDIFF(mm,0,GETDATE()), 0)
        THEN 'MonthCount'
        WHEN ProductSoldDate >= DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0)
        THEN 'YearCount'
    END as lbl
FROM Products 
) ProductSales
PIVOT
(
COUNT(ProductId)
FOR lbl IN ([WeekCount], [MonthCount], [YearCount])
) t

Here is the SQL Fiddle.

Good luck.