【问题标题】:Operand data type varchar(max) is invalid for avg operator操作数数据类型 varchar(max) 对 avg 运算符无效
【发布时间】:2020-12-19 06:24:50
【问题描述】:

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

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 运算符无效。

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

【问题讨论】:

  • 正确的解决方案是将数字存储在数字数据类型中......
  • 为什么将数字存储在varchar 列中?你不应该这样做
  • 这与您之前的问题几乎相同...您已经获得了答案...关于将 varchar 转换为数字以及处理出现的问题,您还有什么不了解的由于使用了不正确的数据类型?
  • 这能回答你的问题吗? select, avg statement not working

标签: sql sql-server sqldatatypes


【解决方案1】:

根据查询中的命名约定,假设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 子句中。

【讨论】:

    【解决方案2】:

    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
    

    【讨论】:

    • 我已转换为浮点数,但出现如下错误:将数据类型 varchar 转换为浮点数时出错。
    • @NamedJustin 这与您之前的问题的原因相同,某些数据不会自然地转换为数字类型。如果您需要进一步的帮助,您需要发布一些示例数据。
    猜你喜欢
    • 2013-06-14
    • 1970-01-01
    • 2017-01-24
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多