Search code examples
sql-serveradventureworks

Create function with 3 parameters - beginningyear, endingyear and month


The function then calculates and returns the total sale for the requested month of the requested years. If there was no sale for the requested period, returns 0

I tried this function, but I don't understand what to do next.

I don't think, the logic is correct.

  CREATE Function sales
     (@BeginningYear int, @EndingYear int, @Month int)
    RETURNS @DateList TABLE (StartDate int, EndDate int, Month int,TotalSales int)
    AS BEGIN
    DECLARE @SUM int = 0
    SELECT SUM(TotalDue) From Sales.SalesOrderHeader
    Where CAST(ORDERDATE as month) = @Month AND CAST(ORDERDATE as year) = @BeginningYear
    AND CAST(ORDERDATE as year)= @EndingYear
    Group by OrderDate
    RETURN;
    END

Screenshot of the table


Solution

  • Try the following:

    CREATE Function sales
         (@BeginningYear int, @EndingYear int, @Month int)
        RETURNS Numeric (12,4)
        AS BEGIN
        DECLARE @SUM Numeric (12,4) = 0
        SELECT @SUM = SUM(TotalDue) From Sales.SalesOrderHeader
        Where CAST(ORDERDATE as month) = @Month AND CAST(ORDERDATE as year) Between @BeginningYear
        AND @EndingYear
        RETURN @SUM;
        END