Sql计算平均值

时间:2013-11-23 14:53:54

标签: sql sql-server-2008

我有一个包含4列RegionName,TownName,CropName,Pests

的表

我想计算特定作物在同一城镇某个地区的平均害虫数量。


|区名| TownName | CropName | Pests |

|拉瓦尔品第| pindi ------------ | CIM 506 --- | 3.3 |

|拉瓦尔品第| pindi ------------ | CIM 506 --- | 3.8 |

|拉瓦尔品第----- | Muree -------------- | CIM 506 --- | 3.5 |

所以区域名称Rawalpindi在相同的城镇名称,即pindi使用相同的作物,即CIM ​​506我想计算那里的有害生物的平均数量答案将是(3.3 + 3.8)/ 2

这是我到目前为止所尝试的......

SELECT DistrictName,TownName, avg(cast(Pests as float))as pest

  FROM [dw_staging].[dbo].[StagingTable]
  group by TownName
GO

它无法正常工作。

2 个答案:

答案 0 :(得分:2)

您只需更新您的论坛。您要选择但不会应用聚合函数的任何列(例如avg,sum,max ...)必须是分组的一部分:

SELECT T.DistrictName, T.TownName, T.CropName, avg(T.pest)
FROM (
    SELECT DistrictName, TownName, CropName, cast(Pests as float) as pest
    FROM [dw_staging].[dbo].[StagingTable]
) as T
group by T.DistrictName, T.TownName, T.CropName
GO

这意味着,对于给定的(区,镇,作物),计算有害生物平均值。

答案 1 :(得分:0)

-- Solution #1
SELECT  DistrictName, TownName, CropName,
        AVG(CAST( CASE WHEN ISNUMERIC(Pests)=1 THEN Pests END AS FLOAT)) AS AvgPest
FROM    [dw_staging].[dbo].[StagingTable]
GROUP BY DistrictName, TownName, CropName;

-- Solution #2
SELECT  DistrictName, TownName, CropName, AVG(CAST( CASE WHEN ISNUMERIC(Pests)=1 THEN Pests END AS FLOAT)) OVER(PARTITION BY DistrictName, TownName, CropName) AS AvgPest
FROM    [dw_staging].[dbo].[StagingTable];