Frage

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

War es hilfreich?

Lösung

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.

Andere Tipps

Using the DATEADD function

In some circumstances, you might want to add an interval of time to a DATETIME or SMALLDATETIME value or subtract an interval of time. For example, you might need to add or subtract a month from a specific date. You can use the DATEADD function to perform this calculation. The function takes the following syntax:

DATEADD(date/time_part, number, date)

Example:

SELECT OrderDate, DATEADD(mm, 3, OrderDate) AS NewDate
FROM Sales.Orders
WHERE OrderID = 1001

Using the DATEDIFF function

The DATEDIFF function calculates the time interval between two dates and returns an integer that represents the interval. The function takes the following syntax:

DATEDIFF(date/time_part, start_date, end_date)

Example:

SELECT OrderDate, DelivDate,
    DATEDIFF(hh, OrderDate, DelivDate) AS HoursDiff
    FROM Sales.Orders
    WHERE OrderID = 1002
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top