操作数数据类型varcharmax对avg运算符无效

问题描述

有人可以帮助我解决这个错误吗?

SELECT 
   a.id,a.name,a.Report,b.Agentid,count(distinct b.pyID),count(distinct b.SourceID),AVG(b.ChatDurationMinute) 
from table_1 a 
left join table_b b on a.id = b.agentid 
where 
   StartChatTime >= ''20200701'' and 
   LastChatTime <= ''20200831''  
GROUP BY a.id,b.AgentID

并得到这样的错误:

操作数数据类型varchar(max)对avg运算符无效。

我该怎么办?感谢任何帮助我的人。

解决方法

根据查询中的命名约定,假设StartChatTimeLastChatTime位于b中而不是a中是非常合理的。如果是这样,则WHERE子句会将LEFT JOIN变成INNER JOIN

此外,在b.AgentId中包含GROUP BY是多余的,因为ON子句指定它应该与a.id相同。

将数字存储在字符串中是一种糟糕的设计。但是,如果您遇到糟糕的设计,应该使用try_()函数之一。

让我假设ChatDurationMinute是一个整数。然后:

SELECT a.id,a.name,a.Report
       COUNT(DISTINCT b.pyID),COUNT(DISTINCT b.SourceID),AVG(TRY_CONVERT(int,b.ChatDurationMinute) * 1.0)
FROM table_1 a LEFT JOIN
     table_b b 
     ON a.id = b.agentid AND
        b.StartChatTime >= '20200701'' AND 
        b.LastChatTime <= '20200831'  
GROUP BY a.id,a.Report;

如果这些日期确实在a中,则可以将其保留在WHERE子句中。

,

ChatDurationMinute列的数据类型似乎是varchar-因此您需要对其进行转换

SELECT 
   a.id,a.Report,b.Agentid,count(distinct b.pyID),count(distinct b.SourceID),AVG(cast(b.ChatDurationMinute as float)) 
from table_1 a 
left join table_b b on a.id = b.agentid 
where 
   StartChatTime >= ''20200701'' and 
   LastChatTime <= ''20200831''  
GROUP BY a.id,b.AgentID

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...