Avg Sql Query始终返回int

时间:2013-11-18 21:19:41

标签: sql sql-server-2008

我的Farmer Names有一列,我的表Town Names有一列TRY

我想找Average_Number_Of_Farmers_In_Each_Town

Select TownName ,AVG(num) 
FROM(Select TownName,Count(*) as num From try Group by TownName) a 
group by TownName;

但此查询始终返回int个值。我怎样才能在float获得价值?

2 个答案:

答案 0 :(得分:2)

您的查询始终在逻辑上返回int ,因为平均值没有做任何事情。内部和外部查询都按城镇名称进行分组 - 因此每个平均值都有一个值,平均值就是计数。

如果您正在寻找整体平均值,那么就像:

Select AVG(cast(cnt as float)) 
FROM (Select TownName, Count(*) as cnt
      From try
      Group by TownName
     ) t

您也可以在没有子查询的情况下执行此操作:

select cast(count(*) as float) /count(distinct TownName)
from try;

编辑:

假设镇上的每个农民都在try中有一排。您是否只想计算每个城镇不同农民的数量?假设你有一个像FarmerName这样的字段来识别给定的农民,那就是:

select TownName, count(distinct FarmerName)
from try
group by TownName;

答案 1 :(得分:2)

;WITH [TRY]([Farmer Name], [Town Name])
AS
(
    SELECT N'Johny', N'Bucharest' UNION ALL 
    SELECT N'Miky',  N'Bucharest' UNION ALL 
    SELECT N'Kinky', N'Ploiesti'
)
SELECT  AVG(src.Cnt) AS Average
FROM
(
    SELECT  COUNT(*)*1.00 AS Cnt
    FROM    [TRY]
    GROUP BY [TRY].[Town Name]
) src

结果:

Average
--------
1.500000

如果没有... *1.00,结果将是(!)1(AVG(INT 2 , INT 1) -truncated-> INT 1,请参阅Return types部分。)