Sql计算平均值

时间:2013-11-23 16:27:45

标签: sql sql-server sql-server-2008

我正在尝试计算一个城镇使用相同种类作物的平均害虫数量。

DistrictName    | TownName           | CropName    |Pests   
Rawalpindi      | pindi              | CIM 506     | 3.3     
Rawalpindi      | pindi              | CIM 506     | 3.8     
Rawalpindi      | Muree              | CIM 506     | 3.5 

但是这个查询继续给我语法错误,即无效列名PestPopulation1,因为我彻底检查了我的列名称的拼写... PestPopuplation属于varchar(max)类型< / p>

以下是我的查询

SELECT T.DistrictName, T.TownName, T.VarietyOfCrop, avg(T.PestPopulation1)
FROM (
    SELECT DistrictName, TownName,VarietyOfCrop, cast(PestPopulation1 as float) as Pests
    FROM FinalTable2
) as T
group by T.DistrictName, T.TownName, T.VarietyOfCrop

5 个答案:

答案 0 :(得分:4)

这会给您带来错误的原因是您为表达式cast(PestPopulation1 as float)添加了别名Pests

您应该在外部查询中使用该别名,如下所示:

SELECT T.DistrictName, T.TownName, T.VarietyOfCrop, avg(T.Pests)
FROM (
    SELECT DistrictName, TownName,VarietyOfCrop, cast(PestPopulation1 as float) as Pests
    FROM FinalTable2
) as T
group by T.DistrictName, T.TownName, T.VarietyOfCrop

您应该能够通过将cast推入avg来简化此查询,如下所示:

SELECT
    DistrictName
,   TownName
,   VarietyOfCrop
,   avg(convert(float, PestPopulation1)) as avg_pests
FROM FinalTable2
group by T.DistrictName, T.TownName, T.VarietyOfCrop
  

将数据类型nvarchar转换为float时出错。我PestPopulation1中的varchar(max)列。

您需要使用CONVERT代替CAST(见上文)。

答案 1 :(得分:4)

如上所述,问题在于您引用了该范围内不可用的列。

总而言之,使用这样一个人为的查询甚至没有充分的理由。这应该也可以,并且更具可读性:

SELECT T.DistrictName, T.TownName, T.VarietyOfCrop, avg(cast(T.Pests as float))
FROM FinalTable2 T
group by T.DistrictName, T.TownName, T.VarietyOfCrop

答案 2 :(得分:0)

试试这个

SELECT T.DistrictName, T.TownName, T.VarietyOfCrop, avg(T.PestPopulation1)
FROM (
    SELECT DistrictName, TownName,VarietyOfCrop, cast(Pests as float) as PestPopulation1 
    FROM FinalTable2
) as T
group by T.DistrictName, T.TownName, T.VarietyOfCrop

答案 3 :(得分:0)

为什么不(仅使用CONVERT而不是CAST):

SELECT DistrictName, TownName,VarietyOfCrop, AVG(CONVERT(float, PestPopulation1)) as Pests
FROM FinalTable2
GROUP BY DistrictName, TownName,VarietyOfCrop

您的查询中的错误是您正在引用表T没有的列。派生表T具有ColumnName,TownName,VarietyOfCrop和Pests列,并且您正在引用那里不存在的PestPopulation1列。

答案 4 :(得分:0)

您的子查询中使用了错误的列名, PestPopulation1 的别名是 Pests ,请找到更正后的查询:

SELECT T.DistrictName, T.TownName, T.VarietyOfCrop, avg(T.Pests)  
FROM (  
SELECT DistrictName, TownName,VarietyOfCrop, cast(PestPopulation1 as float) as Pests  
FROM FinalTable2
) as T  
group by T.DistrictName, T.TownName, T.VarietyOfCrop