【问题标题】:SQL Server stored procedure is calculating a wrong average per stateSQL Server 存储过程计算每个状态的错误平均值
【发布时间】:2016-10-26 03:10:11
【问题描述】:

我有两张桌子

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)  

每个状态并更新列

【问题讨论】:

  • FWIW: AVG(INT) -> INT.
  • 对不起这是什么
  • 平均计算怎么错了?
  • 您提供的样本数据在您的基金表中具有相同的所有行业值,但我猜问题出在这部分:(select Avg(funddetails.Industry*Industrydetails.price) OVER (partition BY Industrydetails.state)) 摆脱选择并简单地使用@987654330 @ 看看这是否给出了您期望的结果。
  • @ZLK 如果我删除选择然后我收到错误窗口函数只能出现在 SELECT 或 ORDER BY 子句中。

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


【解决方案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

【讨论】:

    【解决方案2】:

    我认为您的查询给出了正确的答案。 您在表中添加数据的方式使得 (funddetails.Industry * Industrydetails.price) 和 AVG (FundDetails.Industry * IndustryDetail.Price) 的结果相同

    【讨论】:

      猜你喜欢
      • 2017-03-07
      • 2012-06-25
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      • 2023-03-24
      • 1970-01-01
      • 2016-10-02
      • 1970-01-01
      相关资源
      最近更新 更多