2016-10-26 67 views
1

一個錯誤的平均我有兩個表SQL Server存儲過程是計算每狀態

Funddetails

FundId Fund Industry State Column1 
----------------------------------------- 
    1  1  2  NSW    
    2  1  2  ACT   
    3  1  2  VIC   
    4  1  2  NSW   
    5  1  2  ACT   
    6  1  2  VIC   
    7  1  2  NSW   
    8  1  2  ACT   
    9  1  2  VIC  

Industrydetail

IndustryId price State 
----------------------- 
    1   12 NSW 
    2   1 Vic 
    3   3 ACT 

這是怎麼了更新列1

UPDATE FundDetails 
SET Column1 = CASE 
       WHEN (funddetails.Industry * Industrydetails.price - 
         (select Avg(funddetails.Industry * Industrydetails.price) OVER (partition BY Industrydetails.state)) <= -5 
        THEN '50' 
        ELSE '100' 
       END 
FROM FundDetails 
INNER JOIN Industrydetails ON FundDetails.State = Industrydetails.State 

但是平均的計算結果是錯誤的。

funddetails.Industry*Industrydetails.price(select Avg(funddetails.Industry*Industrydetails.price) OVER (partition BY Industrydetails.state))給出了相同的結果。

是否有任何其他方式獲得

average(funddetails.Industry * Industrydetails.price) 

每狀態和更新列

+0

FWIW:AVG(INT) - > INT。 – user2864740

+0

抱歉,這是什麼 –

+0

平均計算錯誤如何? – ZLK

回答

1
;WITH AvgIndustryPrice (State, AverageIndustryPrice) AS 
(
    SELECT 
     FundDetails.State, 
     AVG (FundDetails.Industry * IndustryDetail.Price) 
    FROM 
     FundDetails 
    JOIN 
     IndustryDetail 
    ON 
     FundDetails.State = IndustryDetail.State 
    GROUP BY 
     FundDetails.State 
) 
UPDATE 
    FundDetails 
SET 
    Column1 = 
    CASE 
     WHEN funddetails.Industry * Industrydetails.price - AvgIndustryPrice.AverageIndustryPrice <= -5 
     THEN '50' 
     ELSE '100' 
    END 
FROM 
    FundDetails 
JOIN 
    AvgIndustryPrice 
ON 
    FundDetails.State = AvgIndustryPrice.State 
0

我想你的查詢給出正確的答案。 (基金行業* Industrydetails.price)和AVG(基金詳細信息。行業* IndustryDetail.Price)