SQL Server存储过程正在计算每个状态的错误平均值

时间:2016-10-26 03:10:12

标签: sql sql-server sql-server-2008 stored-procedures average

我有两张桌子

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)  

每个状态并更新列

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我认为您的查询给出了正确的答案。 您在表格中添加了数据,以便为两者(funddetails.Industry * Industrydetails.price)和AVG(FundDetails.Industry * IndustryDetail.Price)提供相同的结果