销售退货清单总和而不是总额

时间:2016-04-24 22:19:11

标签: sql-server sql-server-2008

我试图获得客户所有销售额的总和,问题是UDF正在返回销售清单。

我尝试更改代码,但我只是无法让销售商品返回值的总和。

任何人都可以帮忙解决这个问题。

---UDF--------------
    ALTER FUNCTION [dbo].[UDF_CalculateCostOfAllSalesItemsSold] 
(
    -- Add the parameters for the function here
    @ProductID nvarchar(50),    
    @Cust nvarchar(50)
)
RETURNS Decimal(18,2)
AS
BEGIN
    -- Declare the return variable here
    DECLARE @CheapestPrice Decimal(18,2)
    SELECT  @CheapestPrice = (Select MIN(s.price) from dbo.Suppliers s where s.SalesItem = @ProductID)
    DECLARE @Price AS DECIMAL(18,2)

    -- Add the T-SQL statements to compute the return value here
    select @Price = (SELECT Sum(@CheapestPrice*i.Qty) AS MinPrice
FROM            dbo.Customers AS c INNER JOIN
                         dbo.Sales AS o ON c.CustomerName = o.Cust INNER JOIN
                         dbo.SalesItemsPurchased AS i ON i.OrderNo = o.OrderNo INNER JOIN
                         dbo.Suppliers AS s ON i.SalesItem = s.SalesItem
WHERE        i.SalesItem = @ProductID AND o.Cust = @Cust)



    -- Return the result of the function


    RETURN @Price



END        
-----Query------------

    SELECT c.CustomerName AS 'CustomerName',  c.CustomerAddress AS 'CustomerAddress',SUM(dbo.UDF_CalculateCostOfAllSalesItemsSold(s.SalesItem, c.CustomerName)) AS 'New Balance'
FROM CUSTOMERS c
left JOIN Sales o
ON c.CustomerName = o.cust
LEFT JOIN SalesItemsPurchased i
on i.OrderNo = o.OrderNo
LEFT JOIN Suppliers s
on i.SalesItem = s.SalesItem 
group by c.CustomerName, c.CustomerAddress,s.SalesItem

---Results returned


 Cust1   17.45
    Cust1   17.45
    Cust1   3.00
    Cust1   0.69
    Cust1   61.44
    Cust2   NULL
    Cust3  30.54
    Cust3  30.54
    Cust3  10.47
    Cust3  10.47
    Cust3  122.88

我之后说的是cust3 = Cust3 163.89

1 个答案:

答案 0 :(得分:0)

SELECT x.CustomerName,
    x.CustomerAddress, 
NewBalance = SUM(ISNULL(x.[New Balance],0)) 
FROM (
        SELECT c.CustomerName AS 'CustomerName',
 c.CustomerAddress AS 'CustomerAddress',
SUM(dbo.UDF_CalculateCostOfAllSalesItemsSold(s.SalesItem, c.CustomerName)) AS 'New Balance'
 FROM CUSTOMERS c 
left JOIN Sales o ON c.CustomerName = o.cust 
LEFT JOIN SalesItemsPurchased i on i.OrderNo = o.OrderNo 
LEFT JOIN Suppliers s on i.SalesItem = s.SalesItem 
group by c.CustomerName,
 c.CustomerAddress,
s.SalesItem
) AS [x]
GROUP BY x.CustomerName
x.CustomerAddress;

您希望再次总结这些值。 但是使用这样的函数不能很好地扩展,你将会看到性能问题。

你可能想问问自己这些LEFT JOINs是否真的有必要。