操作数数据类型varchar(max)对于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, a.name, a.Report, b.AgentID

得到这样的错误:

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

我该怎么办?感谢所有帮助我的人。

根据查询中的命名约定,假设StartChatTimeLastChatTimeb而不是a中是非常合理的。如果是,则WHERE子句将LEFT JOIN转换为INNER JOIN

此外,在GROUP BY中包含b.AgentId是多余的,因为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.name, a.Report;

如果这些日期确实在a中,那么您可以将它们保留在WHERE子句中。

ChatDurationMinute列的数据类型似乎是varchar,因此需要将其转换为

SELECT 
a.id, a.name, 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, a.name, a.Report, b.AgentID

最新更新