使用3个参数创建函数-起始年,结束年和月

时间:2018-07-15 02:02:06

标签: sql-server adventureworks

该函数然后计算并返回总销售额  在要求年份中的要求月份。如果有  在请求的期间内没有销售,返回0

我尝试了此功能,但是我不知道下一步该怎么做。

我不认为,逻辑是正确的。

  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

1 个答案:

答案 0 :(得分:0)

尝试以下操作:

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