您好我正在尝试计算结果集的平均值,但我无法这样做,选择count(*)的查询会返回1月1日到31日之间每天的通话计数,因此返回了近20行。如何计算结果的平均值,然后将值分配给变量,如SET @abc =(下面的查询)。我正在使用sql server 2005。
SELECT avg(Calls) AS average
FROM
(
SELECT COUNT(*) Calls
FROM abc
WHERE CallDate BETWEEN '20120101' AND '20120131'
AND datepart(Hh,TranscribeDateTime) = '07'
AND datepart(Mi,TranscribeDateTime) BETWEEN '00' AND '59'
AND AppID = 123 AND Status ='T'
GROUP BY calldate
)
如果我的方法有误,请提出一个。谢谢
答案 0 :(得分:6)
看起来你只是缺少派生表的表别名(在SQL Server中需要)和赋值语句(如果要将列AS average
分配给变量,也不能为列DECLARE @ABC INT;
SELECT @ABC = AVG(Calls)
FROM
(
SELECT COUNT(*) Calls
FROM abc
WHERE CallDate BETWEEN '20120101' AND '20120131'
AND datepart(Hh,TranscribeDateTime) = '07'
AND datepart(Mi,TranscribeDateTime) BETWEEN '00' AND '59'
AND AppID = 123 AND Status ='T'
GROUP BY calldate
) T /* <-- Alias here */
添加别名)< / p>
{{1}}