2016-04-24 70 views
0

我試圖獲得客戶所做的所有銷售總和,問題在於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

+0

您是否期待每個客戶有單行? – Shaneis

+0

嗨Shaneis是的,但我無法解決如何去做 –

回答

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是否真的有必要。