SQL函数,当没有从查询返回的记录时返回0

时间:2018-02-25 22:48:37

标签: sql sql-server

我创建了以下函数,以返回作为输入输入的特定年份,月份和区域的总销售额。但是如果输入参数没有销售,我需要返回0。我尝试了IFNULL功能,但它似乎不起作用。

Create Function GetTotalSales(@Year int,@month int,@TerritoryID int)
Returns Table
As
    Return (Select Sum(TotalDue) as TotalSales, Cast(OrderDate AS DATE) as OrderDate, TerritoryID       
            From AdventureWorks2008R2.Sales.SalesOrderheader
            Where @Year=DATEPART(Year,OrderDate) and @month=DATEPART(Month,OrderDate) and @TerritoryID=TerritoryID  
            Group By OrderDate, TerritoryID
           );
Go

2 个答案:

答案 0 :(得分:0)

您可以在单个查询中表达:

with r as (
      Select Sum(TotalDue) as TotalSales, Cast(OrderDate AS DATE) as OrderDate, TerritoryID       
      From AdventureWorks2008R2.Sales.SalesOrderheader
      Where @Year = DATEPART(Year, OrderDate) and @month = DATEPART(Month, OrderDate) and @TerritoryID = TerritoryID  
      Group By OrderDate, TerritoryID
     )
select *
from r
union all
select TotalSales, OrderDate, TerritoryId
from (select 0 as TotalSales, NULL as OrderDate, @TerritoryId as TerritoryId
     ) x
where not exists (select 1 from r);

答案 1 :(得分:0)

您还可以考虑以下方法。通过构造一个具有单个“默认”行的表,然后无条件地左键连接到该表,我们确保结果始终包含至少一行。

CREATE FUNCTION GetTotalSales(@year INT, @month INT, @territoryID INT)
RETURNS TABLE
AS
RETURN 
(
    SELECT
        ISNULL(TotalSales, 0) AS TotalSales
        ,OrderDate
        ,TerritoryID

    FROM
        (VALUES (0)) AS default_values(default_value) 

    LEFT JOIN
    (
        SELECT 
            SUM(TotalDue)               AS TotalSales
            ,CAST(OrderDate AS DATE)    AS OrderDate
            ,TerritoryID

        FROM 
            AdventureWorks2008R2.Sales.SalesOrderheader

        WHERE 
            (@year=DATEPART(Year,OrderDate))
            AND 
            (@month=DATEPART(Month,OrderDate))
            AND
            (@territoryID=TerritoryID)

        GROUP BY 
            OrderDate, TerritoryID

    ) AS source_data
    ON (1=1)
);